I'm using the React Router V4 and I've this router's configuration:
<Router history={customHistory}>
<Switch>
<Route exact path={`/:lng?`} component={Page} />
<Route path={`/:lng?/firstUrl`} component={Page}/>
<Route path={`/:lng?/secondUrl`} component={Page}/>
<Route component={NoMatch} />
</Switch>
</Router>
The lng
is optional language parameter which should match pattern like a en
, de
or absent.
For instance app utilizes these routes:
www.website.com/en
www.website.com/en/
www.website.com/ - will load default lang
www.website.com - will load default lang
www.website.com/de
www.website.com/de/
Also I've additional component inside which I define routes for functions:
<ModalRoute component={SomeURL} path={`/:lng?/SomeURL`} parentPath={`/${lang}/`} />
<ModalRoute component={SomeURL2} path={`/:lng?/SomeURL2`} parentPath={`/${lang}/`} />
So as the result I would like to achieve that only allowed language codes (and empty param) would be accepted and which don't - would be redirected to NoMatch
component.
Is it possible? How it could be achieved?
Example much appreciated
Using React Router, when you want to create a Route that uses a URL parameter, you do so by including a : in front of the value you pass to Route 's path prop. Finally, to access the value of the URL parameter from inside of the component that is rendered by React Router, you can use React Router's useParams Hook.
To add in an optional path parameter in React Router, you just need to add a ? to the end of the parameter to signify that it is optional. And then in your component you could access the GET parameters using the location.search prop that is passed in by React Router.
To restrict access to routes in React Router, we set the render prop to a function that renders the component we want according to the condition we're checking. import { Route, Redirect } from "react-router"; <Route exact path="/" render={() => (loggedIn ?
If you are using react-router v4, you can pass it using the render prop. Sometimes you need to render whether the path matches the location or not. In these cases, you can use the function children prop.
You can use regex in your path.
For a required parameter with specified options:
<Route path="/about/:lang(en|de)/" exact component={About}/>
For an optional paramater:
<Route path="/about/:lang?/" exact component={About}/>
For an optional parameter with specified options
<Route path="/about/:lang(en|de)?/" exact component={About}/>
For further reading
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With