Osama Salman
Osama Salman

Reputation: 49

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

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?

Upvotes: 1

Views: 125

Answers (2)

Lajos Arpad
Lajos Arpad

Reputation: 76414

You can create a regex-based route, like:

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

Upvotes: 1

Evren
Evren

Reputation: 4410

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>

Upvotes: 0

Related Questions