I am using react for creating a sample page which has server side rendering using renderToString() for SEO friendly pages.
this is my server.js code
app.get('*', (req, res) => {
match(
{ routes, location: req.url },
(err, redirectLocation, renderProps) => {
// in case of error display the error message
if (err) {
return res.status(500).send(err.message);
}
// generate the React markup for the current route
let markup;
if (renderProps) {
markup = renderToString(<RouterContext{...renderProps}/>);
} else {
res.status(404);
}
// render the index template with the embedded React markup
return res.render('index', { markup });
}
);
});
My page is search page which is static initially and when the user enters the input it fetches data from backend and renders a list of components in the same page.
When I see view page source in browser, I can see only the initial static content, not the html of list which renders after the backend response.
What is the right method to get the updated HTML when the component state changes.
2
Answers
Save the fetched data to your state and the component will re-render itself. That way your view will render the new content when it’s fetched from the backend.
You still need to include your component, and React itself, on your clientside and call
React.render
on the same base element in the DOM.Simply serving the result of
React.renderToString
as static HTML does will only do exactly that, serve static html.If you want your component to get mounted properly on the clientside so it can react to clientside events and re-render for state changes, you’ll need to mount it on the static html, this is done by calling
React.render
on page load on the clientside.There’s more about this here: https://strongloop.com/strongblog/node-js-react-isomorphic-javascript-why-it-matters/