Search code examples
javascriptreactjsreact-routerjsxurl-routing

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>
        );
    }

Solution

  • 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>
        );
    }