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

174
Visualizações
How can sub paths be defined by omitting the parent path with React-Router-Dom?

So, let's say I have Profile page which renders different components according to the path. For example:

/profile/posts renders Posts component inside Profile.

/profile/comments renders Comments component inside Profile.

I normally first render Profile page for "/profile" path and then inside it, render relevant Component according to the Routes mentioned above. What I would like to do is, omit the "/profile" part of the paths defined in Route components inside Profile and only keep the remaining part. How can that be done by not breaking the routing ?

See the comments in the code below:

// App.js

// ...

<Switch>
    <Route exact path="/">
      <Home />
    </Route>
    <Route path="/profile">  // Profile page is rendered here
      <Profile />
    </Route>
</Switch>

// ...
// Profile.js

// ...

<Switch>
    <Route exact path="/profile/posts">  // I want to omit "/profile" part of the path.
      <Posts />
    </Route>
    <Route path="/profile/comments">  // I want to omit "/profile" part of the path.
      <Comments />
    </Route>
</Switch>
// ...
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

When nesting routes if you don't want to "duplicate" path details then you can get them from the match object, specifically the path value for building nested routes.

Assuming Profile is a function component, use the useRouteMatch hook to access the currently matched route's path value. If it is a class component then it will have to access route props to get this.props.match.

// Profile.js

const { path } = useRouteMatch();

// ...

<Switch>
  <Route path={`${path}/posts`}> 
    <Posts />
  </Route>
  <Route path={`${path}/comments`}>
    <Comments />
  </Route>
</Switch>

// ...

Here's a more in-depth nested routing demo from `react-router-dom.

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