A
A
Artyom2020-05-06 21:53:18
React
Artyom, 2020-05-06 21:53:18

How to set up a redirect in react-router-dom?

There is a switch

<Switch>
            <Route path="/contacts" exact>
                <ContactsPage />
            </Route>
            <Route path="/contacts/add" exact>
                <AddContactForm />
            </Route>
            <Redirect to="/contacts" />
 </Switch>

In theory, it should only redirect the user to /contacts if the routes above fail. So, how to make it so that if these two routes do not work, a redirect to /contacts occurs, and not in any case?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Suntsev, 2020-05-07
@airman66

You don't need a redirect for this, just set the default route

<Switch>
            <Route path="/contacts" exact>
                <ContactsPage />
            </Route>
            <Route path="/contacts/add" exact>
                <AddContactForm />
            </Route>
            <Route path="*" >
                <ContactsPage />
            </Route>
 </Switch>

And according to the correct one, I would make it so that the internal route (/contacts/add) would be defined with an exact match, and the external one (/contacts) without it, well, the order would be changed
<Switch>
            <Route path="/contacts/add" exact>
                <AddContactForm />
            </Route>
            <Route path="/contacts">
                <ContactsPage />
            </Route>
 </Switch>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question