Kholiavko
Kholiavko

Reputation: 334

React router call the same code in each route component

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?

Upvotes: 0

Views: 940

Answers (1)

Jacob
Jacob

Reputation: 78920

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>
     );
  }
}

Upvotes: 1

Related Questions