Redirect any other routes to "/" in Router (React JS)

Viewed 59

I have a Router component which routes to different elements depending on the path:

<Router>
    <Route exact path='/' component={RouterPage}/>
    <Route exact path='/sign-up' component={SignUp}/>
    <Route exact path='/lobby' component={Lobby}/>
    <Route exact path='/game' component={Game}/>
    <Route exact path='/game/host' component={Host}/>
    <Route exact path='/debug' component={Debug}/>
</Router>

However, I want to redirect any other path to "/". For example, if the path were to be "/qwerty", it would get routed to "/".

I tried using <Redirect from="*" to="/" />, but it overrides the other defined routes as well.

How could this issue be solved?

2 Answers

You can create a regex-based route, like:

<Route path='/!(sign-up|lobby|game|game/host|debug)' component={RouterPage} />

You can set Link inside your component and add somewhere like header in that page.

import {Link} from 'react-router-dom';
<Link to="/"> Home</Link>
Related