0

I have a React application that uses a Drawer to wrap child components in it. A child component is rendered when a <Route> matches the path in a <Switch>.

In the stateful Drawer component, I want to handle events raised by clicks in the toolbar or sidebar, but currently, I use this.props.children.props.history.push("...") to access the history object to navigate to another page.

What if there are two child components in that wrapper?

This is how I wrap each component with a Drawer.

const RouteWithDrawerLayout = ({ component: Component, ...rest }) => {
    return (
        <Route
            {...rest}
            render={props => (
                <PersistentDrawer>
                    <Component {...props} />
                </PersistentDrawer>
            )}
        />
    );
};

<Switch>
    <RouteWithDrawerLayout path="/listing" exact component={Listing} />
    <RouteWithDrawerLayout path="/register" exact component={Register} />
    <RouteWithDrawerLayout path="/auth" exact component={Auth} />
    <RouteWithDrawerLayout path="*" component={NotFoundPage} />
</Switch>

This is how I handle events in the Drawer.

handleClickLogo = () => {
    this.props.children.props.history.push('/');
};
Unomono
  • 236
  • 1
  • 7
  • 2
    you don't need to do that, better option will be use `withRouter` HOC, check [**this answer**](https://stackoverflow.com/questions/44137774/how-to-navigate-dynamically-using-react-router-dom), btw if case of multiple children, `this.props.children` will be an array so you need to specify the index also, like this: `this.props.children[index].props.history.push('/');`, don't forgot to put the check before that. – Mayank Shukla Feb 22 '18 at 04:43
  • Oh thanks @MayankShukla! How could I have missed that? :) I now use export default `withRouter( connect(mapStateToProps, mapDispatchToProps)(PersistentDrawer) );` on my drawer. – Unomono Feb 22 '18 at 04:52
  • working now with that?? – Mayank Shukla Feb 22 '18 at 04:55
  • Yup! I can now access this.props.history.push() in my wrapper component and navigate easily back and forth. – Unomono Feb 22 '18 at 04:56

0 Answers0