Add children Route's in a component React
I am trying to add <route>
in a component inside a routers component, but didn't work. Please, someone can help me? My login page, have a form and I want to just change the form with routes.
I'm using react-router-dom
v5.
-<Login />
--<LoginForm/>
---<Default/>
---<DadosPessoais/>
Routes.js
<Router>
<Route path="/login" exact component={Login}/>
</Router>
Login.js
<div id="login-main">
<div className="container">
<div className="row" id="login-content" className={ForgotPassWordState ? "forgot" : ""}>
<div>
<LoginForm/>
</div>
<BannerAdvogados />
</div>
</div>
</div>
LoginForm.js
<div id="login-form">
<div id="login-logo">
<img src={logo} alt="Page logo"/>
</div>
<div className="title-form">
<h2>Bem-vindo de volta a Page!</h2>
<p>Preencha os campos abaixo e acesse sua conta</p>
</div>
<Route path="/login" exact component={Default} />
<Route path="/login/dados" exact component={DadosPessoais} />
</>
}
</div>
First issue is that the root route is only rendered when it exactly matches "/login"
, so if the URL/path becomes "/login/dados"
it no longer matches exactly and Login
is unmounted.
Remove the exact
prop on the root Route
component so subroutes/nested routes can be matched and rendered.
Login.js
<Router>
<Route path="/login" component={Login} />
</Router>
Second issue, the Router
inclusively (means anything that matches is rendered) matches and renders routes, this is likely why you are trying to use the exact
prop on all the nested routes. Use a Switch
component to exclusively (only the first match is rendered) a route. While you could continue using the exact
prop on all nested routes, it's simpler to render them into a Switch
in descending order of path specificity (i.e. more specific paths before less specific paths).
LoginForm.js
<Switch>
<Route path="/login/dados" component={DadosPessoais} />
<Route path="/login" component={Default} />
</Switch>