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

121
Visualizações
Create dynamic route using list of string as paths in React JS with BrowserRouter

Below is the current implementation of my router which is kind of hard-coded and redundant. I have an object which contains all the path for example like below

path = ["physical-health","general-health","wellbeing"];

I want to make it dynamic to reduce the hard coding and make it more scalable. Something like this.

for (var i = 0; i < path.length-1; i++) {
        <Route exact path={this.state.basePath + path[i]} render={() => <Welcome />} />
    } 

But its doesn't seem to be working inside BrowserRouter.

render() {
        return(
            <BrowserRouter history={history}>
                <div className="">
                    <div id="maincontent">
                        <Route exact path={this.state.basePath +"/physical-health"} render={() => <Welcome />} />
                        <Route exact path={this.state.basePath +"/general-health"} render={() => <Welcome />} />
                        <Route exact path={this.state.basePath +"/wellbeing"} render={() => <Welcome />} />
                    </div>
                </div>
            </BrowserRouter>
        );
    }
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use .map() to do what you're looking for:

path = ["/physical-health","/general-health","/wellbeing"];
path.map(p => <Route exact path={this.state.basePath + p} render={() => <Welcome />} />)

Another way:

path = ["physical-health","general-health","wellbeing"];
path.map(p => <Route exact path={`${this.state.basePath}/${p}`} render={() => <Welcome />} />)

For a full example:

render() 
{
    const path = ["physical-health","general-health","wellbeing"];
    return(
        <BrowserRouter history={history}>
            <div className="">
                <div id="maincontent">
                    {path.map(p => <Route exact path={`${this.state.basePath}/${p}`} render={() => <Welcome />} />)}
                </div>
            </div>
        </BrowserRouter>
    );
}
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