6

I'm building an Isomorphic app using React, react-router v3 and material-ui. One of the requirements of material-ui in server-side rendering is to pass to the theme the client's user agent, so MUI will be able to prefix their inline styles accordingly.

Originally the root component of the app was the router, i.e on the server side:

<RouterContext {...renderProps}/>

And on the client:

<Router children={routes} history={browserHistory} />

Now, since I didn't know how to pass the user agent to the RouterContext on the server, I came up with an (ugly?) solution: I've created a useless component named Root, to whom I passed the user agent, and Root had the router as his children, i.e. on the server side:

<Root userAgent={userAgent}>
  <RouterContext {...renderProps}/>
</Root>

and on the client:

<Root>
  <Router children={routes} history={browserHistory} />
</Root>

Now, everything works well but I don't really like creating that useless element if I don't have to, so my question is - is there a better way?

Can I somehow pass the user agent to RouterContext on the server, which will in turn pass it to the Index Route which will create the theme?

Here's the code of Root if someone's interested:

class Root extends React.Component {
  constructor(props){
    super();
    this.muiTheme = getMuiTheme(customTheme, { userAgent: props.userAgent });
  }

  render () {
    return (
    <MuiThemeProvider muiTheme={this.muiTheme}>
      {this.props.children}
    </MuiThemeProvider>
    );
  }
}
icc97
  • 11,395
  • 8
  • 76
  • 90
Gershon Papi
  • 5,008
  • 3
  • 24
  • 50

1 Answers1

2

You can use createElement on RouterContext to achieve this.

<RouterContext
  {...renderProps}
  createElement={(Component, props) => <Component {...props} userAgent={data.userAgent} />}
/>

This will make userAgent available in the props of all route components.

Matt Cole
  • 2,491
  • 17
  • 21
  • Thanks, I eventually used a dummy component `Root` to which I pass the props, that will be the parent of `RouterContext`. Your solution is better ofcourse :) – Gershon Papi Aug 28 '16 at 05:20