Hayk Shakhbazyan
Hayk Shakhbazyan

Reputation: 242

React-router-dom: Render two components under one route

<Provider store={store}>
    <BrowserRouter>
        <div>
            <Switch>
              <Route
                path="/test/:id"
                component={Question1} />
              <Route
                path="/test/:id"
                component={Question2} />
        </div>
    </BrowserRouter>
</Provider>

I need to navigate from Question1, which has id of 1, to question2 which should have id of 2. I can navigate to question1 from test without problem, but when I want to go to question to using this.props.history.push('/test/2') the URL changes but I dont get navigated to question2.

Any ideas ?

Upvotes: 0

Views: 3078

Answers (3)

palsrealm
palsrealm

Reputation: 5243

You should have a single Question component which handles the id and displays the appropriate question.

You can do the same using the render method of Route

  <Route
     path="/test/:id"
     render={(props)=>{
             switch(props.match.params.id){
                  case "1": return <Question1/>;
                  case "2" : return <Question2/>;
                  default : return null;
              }
     }}
  />

EDIT: Corrected code after comment

Upvotes: 4

Julian Wilson
Julian Wilson

Reputation: 2470

This issue is that <Switch> will match the first component under the <BrowserRouter/> in this case. If it doesn't match the first path, it will try the second. That is how Switch works. So in your example the path template of path=/test/:id actually matches both /test/1 and /test/2, and that Route always renders Question1 and never Question2. Check out the docs here https://reacttraining.com/react-router/web/api/Switch.

One quick thing you can do is if you know you only have two Questions then you can do

          <Route exact
            path="/test/1"
            component={Question1}
          />
          <Route exact
            path="/test/2"
            component={Question2}
          />

Which will solve your problem immediately, but I don't recommend this as it gets unreasonable as you get more Questions. A better set-up is what @palsrealm recommends.

Upvotes: 2

Gabriel Bleu
Gabriel Bleu

Reputation: 10224

You can do this with one route, and load the right question in your component :

<Route path="/test/:id" component={Question} />

// Question.js
export default React.createClass({
  render() {
    return (
      <div>
        <h2>Question {this.props.params.id}</h2>
      </div>
    )
  }
})

doc : route-with-parameters

Upvotes: 0

Related Questions