1

i am trying to generate dynamic route from json.

there is my static router

     <Router history={newHistory}>
        <div>
            <Route path="/home" component={HomeComponent}/>
            <Route path="/foo" component={FooComponent}/>
            <Route path="/bar" component={BarComponent}/>
        </div>
    </Router>

in my json result i get route:{home,foo,bar}

in my case i try to loop on my tab route and creat route without succes ... any idea ?

there is one of my try

listRoute(jsonRoute){

    var tmp;
    for (i = 0; i < jsonRoute.length; i++){
        tmp +=  <Route path="/jsonRoute[i]" component={TestComponent}/>;
    }
    return (
        tmp
    )
}

render() {
    return (
        <div>
            <Router history={newHistory}>
                {
                    this.listRoute()
                }
            </Router>
        </div>

    );
}

thx

1 Answer 1

2

You need to use an Array in listRoute function:

listRoute(jsonRoute){
    var tmp = [];
    for (i = 0; i < jsonRoute.length; i++){
        // you need to concatenate `i` variable as well:
        tmp.push(<Route path={"/" + jsonRoute[i]} component={TestComponent}/>);
    }
    return tmp;
}
Sign up to request clarification or add additional context in comments.

6 Comments

And in general try to move away from var and use let and const to avoid polluting the global namespace.
@Jayce444 in that case we are not polluting global namespace using var keyword, as it's defined in the scope of the function
Yeah I know that's why I said 'in general'. It's best not to use it in any situation and just get used to the other ones that way you reduce the risk of using var in a potentially bad spot. But you're right here it doesn't matter
thx a lot you save me. ps : can you upvote my question i'm new and i need 20 of rep to access to the chat thx a lot
@1ven it's perfect but i change tmp.push(<Route path={"/jsonRoute" + i} component={TestComponent}/>); to tmp.push(<Route path= path={"/" + jsonRoute[i]} component={TestComponent}/>);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.