0
votes
ReactDOM.render(  
  <Provider store={store}>    
      <BrowserRouter>
        <Root />
     </BrowserRouter>
     </Provider>,
  document.getElementById('root')
);

Here is Root.js:

 class Root extends Component {

        componentDidUpdate(prevProps) {      
          if (this.props.location !== prevProps.location) {
           // this.onRouteChanged();
          }
        }
        render(){
            console.log("Router Render")
                return (

                            <div>
                                <Header/>
                                <Route exact path="/" component={Login} />
                                <Route  path="/tabs" component={Tabs} />
                            </div>

                )
        }
    }



    export default withRouter(Root);

I have my Header component at the top of the my site.And I want my Header component to always stay top whenever Routes change. But I want to pass props to my Header Component while Routes are changing.

For example I am at the main Route( path="/") at the start.And I want to pass prop to my Header component( <Header locationinfo="main" /> ).

And if I change the route to "path="/tabs" I want to pass another prop value to my Header component(<Header locationinfo="tabs />)

What is the best practice for that case?

2

2 Answers

0
votes

Use render prop instead of component.

More info: https://reacttraining.com/react-router/core/api/Route/render-func

<Route exact path="/" render={() => {
  <div>
    <Header locationinfo="main" />
    <Login />
  </div>
}} />
<Route path="/tabs" render={() => {
  <div>      
    <Header locationinfo="tabs" />
    <Tabs />
  </div>
}} />
0
votes

If you wrap your Root component with the withRouter HOC, you can pass the react router location prop to your Header:

<div>
  <Header location={props.location} />
  <Route exact path="/" component={Login} />
  <Route  path="/tabs" component={Tabs} />
</div>