Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactRouter v4 - Redirect doesn't work with Switch

I have a code:

import React from 'react';
import ReactDOM from 'react-dom';
import Navigation from './Navigation';
import PublicPage from './PublicPage';
import LoginPage from './LoginPage';
import SecuredPage from './SecuredPage';
import {Route, Switch, Redirect, BrowserRouter} from 'react-router-dom';

ReactDOM.render(
    <BrowserRouter>
        <Navigation>
            <Switch>
                <Redirect from='/' to='/public'/>
                <Route path="/public" component={PublicPage}/>
                <Route path="/login" component={LoginPage}/>
                <Route path="/secured" component={SecuredPage}/>
            </Switch>
        </Navigation>
    </BrowserRouter>,
    document.getElementById("react-app")
);

Now I want path / to redirect to /public path but somehow this configuration doesn't work. Other routes stop rendering as well. I think I do everything like in documentation

like image 733
Tomasz Mularczyk Avatar asked Mar 18 '17 15:03

Tomasz Mularczyk


2 Answers

Swap

<Redirect from='/' to='/public'/>

with

<Redirect exact from='/' to='/public'/>

because otherwise '/' will match everything, creating an infinite redirect loop

like image 61
Ain Avatar answered Oct 03 '22 08:10

Ain


Complementary to rafty answer there is another solution:

ReactDOM.render(
    <BrowserRouter>
        <Navigation>
            <Switch>
                <Route exact path="/">
                    <Redirect from='/' to='/public'/>
                </Route>
                <Route path="/public" component={PublicPage}/>
                <Route path="/login" component={LoginPage}/>
                <Route path="/secured" component={SecuredPage}/>
            </Switch>
        </Navigation>
    </BrowserRouter>,
    document.getElementById("react-app")
);

but of course its not as clean.

like image 41
Tomasz Mularczyk Avatar answered Oct 03 '22 07:10

Tomasz Mularczyk