0

I want to use URL paths for my app. Currently I just render a Main component in app.js:

render() {
  return (
    <Main 
      isLoggedIn={this.state.isLoggedIn}
      user={this.state.user}
      ... />
  )
}

(The props are a bunch of variables and functions)

I tried using react-router but I don't understand how to send props to the child components.

<Router history={browserHistory} >
  <Route path='/' component={Main}
    ... where to send props? />
  <Route path='join' component={Join}
    ... props />
</Router>

The problem is that I need some state variables of my App component (in app.js) to be available in both Main and Join. How do I achieve that with a router?

App structure:

App
 - Join
 - Main
   - ...
yberg
  • 110
  • 2
  • 14

2 Answers2

0

You can use standard URL parameters. For example, to pass an ID:

<Route path='join/:id' component={Join}/>

You'll need to use browserHistory:

browserHistory.push(`/join/${id}`);

Then use this.props.params.id on Join.

Here's a more in-depth explanations https://stackoverflow.com/a/32901866/48869

Community
  • 1
  • 1
Eldelshell
  • 6,683
  • 7
  • 44
  • 63
  • I need to pass several variables as well as some functions, so I don't think this approach will work unfortunately. – yberg Jan 14 '17 at 16:42
  • In that case update your question with what you want to send around so it's easier to understand. – Eldelshell Jan 14 '17 at 17:13
0

It depends how you are managing your state. if you use the Redux, you don't need to pass props in router, you can simple access redux in any component using connect, However if you don't use react then you can use the Redux router's hierarchy functionality

Assume you have a route something like this

<route path="/student" component={studentHome}>
   <route path="/class" component={classHome} />
</route>

when you access the path

/student/class

React router will load the classHome component as children of StudentHome and you can simple pass props to classHome component.

you student class Render method will be something like

render(){
     const childrenWithProps = React.Children.map(this.props.children,
     (child) => React.cloneElement(child, {
       doSomething: this.doSomething
     })
    );

    return <div> some student component functionality
                <div>
                 {childrenWithProps}
                </div>
           </div>
}

more details about passing props to children: How to pass props to {this.props.children}

Community
  • 1
  • 1
abhirathore2006
  • 3,317
  • 1
  • 25
  • 29
  • I need to keep my state one level above both Main and Join though, and I don't see how that would work using this approach. Main and Join are on different paths but need to have access to the same props. – yberg Jan 14 '17 at 16:49
  • I actually managed to solve it by moving the state one level down (to Main), and keep Main as a container route for the rest of the routes/components. Thanks. – yberg Jan 14 '17 at 17:51