Skip to content Skip to sidebar Skip to footer

React Router V4 Global No Match To Nested Route Childs

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'; impor

Solution 1:

I have the same problem with Switch since the following will always render my NoMatch component if I do not go to /a

<Routerhistory={history}><Switch><Routepath='/a'component={A} /><Switch><Routepath='/b'component={B} /><Routepath='/b/:id'component={C} /></Switch><Routepath="*"component={NoMatch}/></Switch></Router>

However, it will work, as expected, if you move your NoMatch inside the nested Switch like this:

<Routerhistory={history}><Switch><Routepath='/a'component={A} /><Switch><Routepath='/b'component={B} /><Routepath='/b/:id'component={C} /><Routepath="*"component={NoMatch}/></Switch></Switch></Router>

Even if this is a 'solution' to the problem it is not what you want since the second Switch is in a different file like the first Route is as well.

So as the application grows and more routes come into play in different files you never know where you need to put the NoMatch route for it to work as expected.

Did you find any other solution to this problem?

Solution 2:

What you could do is define all possibly allowed routes in your root App. Therefore, adapt your App component using optional pattern as follows:

constApp = () => (
    <Router><Switch><Routeexactpath="/"render={() =>  {return <h1>Home</h1> }} />
                <Routepath="/register/(detail)?"exactcomponent={Register} /><Routecomponent={() => {return <h1>Not found!</h1>}} />
        </Switch></Router>
);

Post a Comment for "React Router V4 Global No Match To Nested Route Childs"