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.

David
  • 199
  • 1
  • 13
  • Have you tried using `exact` keyword before `path` inside your `route`? – Sajjad Mar 31 '18 at 15:56
  • yes, but `:locale` is still `undefined` – David Mar 31 '18 at 16:02
  • How are you accessing the `route`? From where you are passing the value of `locale`? – Sajjad Mar 31 '18 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. – David Mar 31 '18 at 16:06

1 Answers1

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);
SrThompson
  • 4,388
  • 2
  • 12
  • 23
  • 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 – SrThompson Mar 31 '18 at 16:27