How can I redirect the user to a NoMatch component when I have nested routes in React Router V4?
Here is my code:
import React from 'react';
import ReactDOM from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
import {
BrowserRouter as Router,
Route,
Switch
}
from 'react-router-dom';
import Website from './website/Website';
const Register = ({ match}) => {
return (
<div>
<Route exact path={match.url} render={() => {return <h1>Register</h1>} } />
<Route path={`${match.url}/detail`} render={()=>{return <h1>Register Detail</h1>}} />
</div>
)
}
const App = () => (
<Router>
<Switch>
<Route exact path="/" render={() => {return <h1>Home</h1> }} />
<Route path="/register" component={Register} />
<Route component={() => {return <h1>Not found!</h1>}} />
</Switch>
</Router>
);
ReactDOM.render(
<App/>, document.getElementById('root'));
As You can see, there is a NoMatch route below Register but I don't want to use the same Route mapping on my child component Register. In this way, if I go to /register/unregisteredmatch the page just show blank because do not enter in NoMatch Route.
How can I map a global NoMatch without specify that on my child route? I don't want to pass this responsability to the child components.
Thanks.
What you could do is define all possibly allowed routes in your root App. Therefore, adapt your App component using optional pattern as follows: