React router call the same code in each route component Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of React router call the same code in each route component without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have the next routes on main component of my app:

<div>
    <h1><Link to="/">Home</Link></h1>
    
    <Switch>
      <Route exact path="/" component={FirstPage} />   
      <Route exact path="/:language?/second" component={SecondPage} />
      <Route exact path="/:language?/account" component={AccountPage} />
      <Route exact path="/:language?/add" component={AddNewPage} />
      <Route component={NoMatch} />
    </Switch>
  </div>

I need to add in each child component checking this.props.match.params.language (this is react-router props) in order to set the current language. But white this code in each componentWiilMount looks wired on my mind. Even I put this checking in a single function and will call it every componentWiilMount and pass this.props.match.params.language props to it, anyway it a mess of code. For example, if I have 100 routes I need to add this checking 100 times. Also, I think about adding this code to the main component lifecycle, and it will be called when the page changed, but I do not have react-router props here. Maybe you know a better solution for this?

Answer

You may want to try nesting your routes. You could have one parent route component that manages the language then nests child route components:

function Root() {
  return ( 
    <div>
      <h1><Link to="/">Home</Link></h1>

      <Route path="/:language?" component={LanguageSelector}/>
    </div>
  );
}

class LanguageSelector extends React.Component {
  componentDidMount() {
    // Manage language (if specified)
  }

  render() {
     return (
       <Switch>
         <Route .../>
         <Route .../>
       </Switch>
     );
  }
}
We are here to answer your question about React router call the same code in each route component - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji