0

The code that I'm working with has controllers in the backend Groovy code which render GSP (Groovy Server Pages). And for the frontend we're using react-router v4 to handle routes. The problem I'm encountering is that by defining a route in react-router, it doesn't allow the browser to fetch anything from the backend and just doesn't render a component (because the template is defined in the backend for that route and not in the frontend).

For example:

<button onClick={() => this.props.history.push('/somethingThatShouldBeRenderedByTheFrontend')}>Render from the frontend</button>
<button onClick={() => this.props.history.push('/somethingThatShouldBeRenderedByTheBackend')}>Render from the backend</button>

And when "Render from the frontend" is clicked, that should render "FrontendReactComponent", but when "Render from the backend" is clicked, it should let Groovy controller called "XYZ" should be hit, which in turn renders a GSP page. I couldn't find the proper terminology to research this problem online. Anyone know what I can search for, or how I can solve this problem?

EDIT: Found more info about this problem here (along with a solution): React-router urls don't work when refreshing or writting manually

ScaVenGerS
  • 61
  • 10

1 Answers1

1

There is no simple fix for what you are trying to do. As you've experienced, the React router can only deal with the state of the loaded front-end application (i.e. the state of the browser, the loaded scripts, etc.)

If you need to let the back end render a whole new page, you can't just push the state (to the front-end router component), you need to basically navigate the browser to a new URL which will make it fetch the page afresh -- even if that looks very similar to the browser's location field and history, it's a very different thing, since it will reload all of the client-side scripts and state.

Also consider how these URLs would work as bookmarks - you'd have to be sure which URLs the back end should be handling, and which ones should just load the client app and then navigate to the requested component.

I'd do something different instead: If you - for some pages - need to render lots of HTML on the server side, make a controller for that, but without headers and footers: Basically make a "back-end mirror" React component that will fetch the desired HTML from the server and render that into a (using the innerHtml property).

JesperSM
  • 1,408
  • 1
  • 10
  • 14
  • That's basically what I'm planning to do: have a controller that return HTML snippets that can be rendered by React using the innerHTML property. Thanks for the help! – ScaVenGerS Sep 19 '18 at 19:58