Ashish Rawat Ashish Rawat - 1 year ago 159
React JSX Question

How to render component in react server side with async data

I searched a lot and didn't find any implementation to load data async in react server side before render the markup without any flux (redux) implementation.
Here's the view (both api and views together):

class Home extends React.Component {
constructor(props) {
this.state = {meta: []};

componentDidMount() {
Request.get('').then((resp) => {
this.setState({meta: resp.body});


render() {
return (
{, i) => {
<p key={i}>{m.user}</p>

The router file (router.js):

export default (
<Route component={App} path="/">
<IndexRoute component={Home}/>

And this is what I use on server (with react-router)

app.use((req, res) => {

Router.match({routes: routes, location: req.url}, (err, redirectLocation, renderProps) => {
if(err) res.status(500).send(err.message);

else if(redirectLocation)
res.status(302).redirect(redirectLocation.pathname +;

else if(renderProps) {
var html = ReactDOM.renderToString(<RouterContext {...renderProps}/>);
res.render("layout", {body: html});
else res.status(404).send("Page not Found");

I know some basic thing that attach api calls to each router url and then resolve the
after that. But I don't understand how to do that with react-router.
I don't want to use any library or flux or redux implementation.

Answer Source

you can use getComponent prop in react-router to handle this situation.

  function fetchAndGetComponent(location,callback){
    Request.get('').then((resp) => {
      let meta = resp.body;
      callback(null,() => <Home meta={meta} />);

  <Route component={App} path="/">
        <IndexRoute getComponent={fetchAndGetComponent}/>