1

My routes are like

<BrowserRouter>
  <App>
    <Switch>
      <Route path="/:locale?" component={Home}/>
    </Switch>
  </App>
</BrowserRouter>

App component is

class App extends Component {
    componentDidMount() {
        if (this.props.match) {
            console.log(this.props.match);
        }
    }
}

I'm getting undefined here. This only works for Home component.

I need some workaround for changing language state according to :locale for every Route. I don't want to do this manually for every route component.

4
  • Have you tried using exact keyword before path inside your route? Commented Mar 31, 2018 at 15:56
  • yes, but :locale is still undefined Commented Mar 31, 2018 at 16:02
  • How are you accessing the route? From where you are passing the value of locale? Commented Mar 31, 2018 at 16:03
  • I'm navigating to localhost:3000/en so that props.match.locale should be en. This works if put same code in all routes. I want to get it in App that wraps all of routes as its children. Commented Mar 31, 2018 at 16:06

1 Answer 1

2

If you don't want to render App inside a Route, you can use the withRouter HOC provided by react-router. In your App component:

import {withRouter} from 'react-router-dom';

class App extends Component {
  ...
}

export default withRouter(App);
Sign up to request clarification or add additional context in comments.

1 Comment

I don't think you can access the locale param since the /:locale? route is being rendered after/inside the App component. You should just set some state in App for the locale. If you want to have locale available everywhere you can use Context

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.