AnApprentice AnApprentice - 3 years ago 176
React JSX Question

How to pass props from React Router 4 to a Container?

I'm working to pass a prop from my router to my layout file but the prop

customClass
is not being passed.

Here is my React app's router:

const WithMainLayout = ({component: Component, ...more}) => {
return <Route {...more} render={props => {
return (
<MainLayout {...props}>
<Component {...props} />
</MainLayout>
);
}}/>;
};

const App = ({store}) => {
return (
<StoreProvider store={store}>
<ConnectedRouter history={history}>
<ScrollToTop>
<Switch>
<WithMainLayout exact path="/" component={Home2} customClass="XXX" />
</Switch>
</ScrollToTop>
</ConnectedRouter>
</StoreProvider>
);
};


the problem
In MainLayout, I'm not getting the customClass prop:

class MainLayout extends React.Component {
componentDidMount() {
console.log(this.props.customClass);
...


This is being logged as
undefined


What am I doing wrong here?

Thanks

Answer Source

Ok so the props argument passed from router to the render method callback does not contain the properties you applied to <WithMainLaout />, it contains history, location, and match. To fix your issue you can do the following:

const WithMainLayout = ({component: Component, ...more}) => {
  return <Route {...more} render={props => {
    return (
      <MainLayout {...props} {...more}>
        <Component {...props} {...more} />
      </MainLayout>
    );
  }}/>;
};

This will give you the properties from both.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download