Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
React router switch doesn't match on first load

I have the below swtich using react-router. When I open a new tab and go to any path it always redirects to /login. If I remove the bottom switch (with no path - the default), it works as expected. If I navigate to any path having already loaded the react app (i.e. from /login), it works as expected.

Why is the switch not detecting the right path apparently only on first load when the nomatch is included?

Edit: for clarity this is using hashRouter on localhost, react-router-dom v5.2

<Switch>
        <div className="loginForm align-middle">
            <img src="./img/logo.svg" alt="Restocker logo" className="w-100 p-3 mb-4"/>
            <Route path="/verify">
                <Verify/>
            </Route>
            <Route path="/reVerify">
                <ReVerify/>
            </Route>
            <Route path="/register">
                <Register/>
            </Route>
            <Route path="/forgotPassword">
                <ForgotPassword/>
            </Route>
            <Route path="/resetPassword">
                <Verify type={"password"}/>
            </Route>
            <Route path="/login">
                <Login/>
            </Route>
            <Route> //same result using path="*"
                //no match - default to login
                <Redirect to="/login"/>
            </Route>
        </div>
    </Switch>

Similar topics don't seem to apply to this scenario - either refer to not matching at all (mine does once loaded) or are from much older (2015) versions.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

It's important to note that the current version of react-router-dom v6 doesn't support the <switch> component instead it uses the <BrowserRouter> which I like to import as <Router>

import {
  BrowserRouter as Router,
  Route,
  Routes,
} from "react-router-dom";

Also, the v6 uses the <element> component to call the component you wish to run on a particular route.

<Router>
    <Navbar/>
    <Routes>
      <Route path="/" element={<Home />} />
       <Route path="about" element={<AboutPage />} />
       <Route path="contact" element={<ContactPage />} />
      </Routes>
    </Router>

which means you will have to import those components as well.

import Navbar from "./components/NavBar";
import Home from "./pages";
import AboutPage from "./pages/aboutPage";
import ContactPage from "./pages/contactPage";

I've included a Navbar component and placed it outside inside the <Router> but outside the <Routes> in order for the nav to appear on all routes. But that's more of a design choice.

You might also run into a problem where your route will open and page at the same area on the screen where you were when clicked on the route. Let me know if you'll need help with that. You might not need it if you're app is no longer than the full page length

about 4 years ago · Juan Pablo Isaza Relatório

0

I thought it would be something silly - the containing div should be outside the switch. It now works as expected (I also changed to using component props instead of children, but both seem to work once the div has been moved).

Working code:

    <div className="loginForm align-middle">
        <img src="./img/logo.svg" alt="Restocker logo" className="w-100 p-3 mb-4"/>
        <Switch>
            <Route path="/verify" component={Verify}/>
            <Route path="/reVerify" component={ReVerify}/>
            <Route path="/register" component={Register}/>
            <Route path="/forgotPassword" component={ForgotPassword}/>
            <Route path="/resetPassword" render={() => Verify("password")}/>
            <Route path="/login" component={Login}/>
            <Redirect to="/login"/>
        </Switch>
    </div>

Note that now all direct children of Switch are now only Route

Edit tweaked based on advice of Drew Reese

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda