0

I am using react-router-dom for my project, but I am a new to it. I have a problem about page jump, Here is my code for App.js:

 class App extends Component {
  render() {
    return (
      <div className="App">
        <Switch>
          <Route
            path="/userrestaurant"
            render={props => <UserRestaurant {...props} />}
          />
          <Route path="/userrestaurant/edit/:id" component={EditRestaurant} />
        </Switch>
      </div>
    );
  }
}

export default App;

Here is code for UserRestaurant component:

 export default class UserRestaurant extends Component {
  edit = () => {
    var restId = 4;
    this.props.history.push(`/userrestaurant/edit/${restId}`);
  };

  render() {
    return (
      <div>
        <Button onClick={this.edit}>Edit</Button>
      </div>
    );
  }
}

It suppose to jump to EditRestaurant component if I click Edit button since I have already define the Route in App.js. But when I click the button, only the url change, the page stay in the UserRestaurant component.

1 Answer 1

2

A <Route/> does a partial match on URLs unless you add an exact prop. In other words, /userrestaurant/edit/blah still matches the first case of the Switch, so UserRestaurant is still rendered. Either add exact so the first one doesn't still match the second URL or reorder your routes so the more specific one comes first.

class App extends Component {
  render() {
    return (
      <div className="App">
        <Switch>
          <Route
            path="/userrestaurant"
            exact
            component={UserRestaurant}
          />
          <Route 
            path="/userrestaurant/edit/:id" 
            component={EditRestaurant} />
        </Switch>
      </div>
    );
  }
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.