0

I want to write a wrapper component that passes any children props. For example in a pure react auth system.

<Router history={ hashHistory } >
<Route path="/" component={Base}>
<Route component={Auth}>
    <Route path="/who" component={Who} />
    <Route path="/features" component={Features} />
    <Route path="/try" component={Try} />
</Route>
</Route>
</Router>

I want to pass a user by props to either the Who, Features or Try components from Auth, which will pull from local storage.

The silly thing I have tried to do is to manipulate this.props or this.props.children but this is not ok, what is the recommended solution?

class Auth extends Component {
  render() {
    //find user or null
    var user = JSON.parse(localStorage.getItem('user')) || [];
    //this.props.user = user;
    console.log('top level router props.user', this.props.user);
    return (
    <div>
    {this.props.children}
    </div>
    );
  }
}
mibbit
  • 4,997
  • 3
  • 26
  • 34
  • you can use `onEnter` Example of a child route will be like this `` – Keshan Nageswaran Nov 06 '16 at 09:35
  • @KeshanNageswaran thanks for the reply, my app is a bit more particular about roles and I want to be able to evaluate a string. I wrote a small wrapper API around the base react component class I can evaluate against I'm just not sure how to pass from the top level. I think I may need to use cloneElement – mibbit Nov 06 '16 at 09:43
  • hope that [react-router-role-authentication] (https://www.npmjs.com/package/react-router-role-authorization) will cater your need i found this [blog post] (http://frontendinsights.com/role-based-authorization-using-react-router/) as well – Keshan Nageswaran Nov 06 '16 at 09:57

2 Answers2

0

see this answer by Jess. React clone element is what you want.

React router and this.props.children - how to pass state to this.props.children

render() {
    var childrenWithProps = React.cloneElement(this.props.children, {someProp: this.state.someProp});
    return (
      <div>
        <Header />
        {childrenWithProps}
      </div>
    );
  }
Community
  • 1
  • 1
mibbit
  • 4,997
  • 3
  • 26
  • 34
0

If you upgrade to version 4 you can use Match with your own HOC for auth.

https://react-router.now.sh/auth-workflow

Garry Taylor
  • 940
  • 8
  • 19