dfsdigging
dfsdigging

Reputation: 345

No children are rendered when the user navigates to a specific route in react router

I have been playing with react router and trying different things and I just ran into this issue.

When user routes to simple localhost:3000, the expected routing happens and I see the ParamsComponent but when user navigates to localhost:3000/netflix which is there is one of the link, I don't see the child component to be rendering on the screen.

Here is my Router config:

<Router>
  <Switch>
    <Route exact path="/" component={ParamsComponent} />
    <Route path="/:id" component={Child} />
  </Switch>
</Router>

Here is my ParamsComponent component:

class ParamsComponent extends React.Component {
  render() {
    return (
      <div>
        <Router>
          <div>
            <h2>Accounts</h2>
            <ul>
              <li>
                <Link to="/netflix">Netflix</Link>
              </li>
              <li>
                <Link to="/zillow-group">Zillow Group</Link>
              </li>
              <li>
                <Link to="/yahoo">Yahoo</Link>
              </li>
              <li>
                <Link to="/modus-create">Modus Create</Link>
              </li>
            </ul>
          </div>
        </Router>
      </div>
    );
  }
}

export default ParamsComponent;

And here is my Child component:

class Child extends React.Component {
  render() {
    const { match } = this.props;
    console.log("child", this.props);
    return (
      <div>
        <h3>ID: {match.params.id}</h3>
      </div>
    );
  }
}

export default Child;

Upvotes: 1

Views: 46

Answers (1)

Tholle
Tholle

Reputation: 112777

You should only have one top level Router so that every Link component gets the same history object through context as your Route components.

Remove Router from ParamsComponent and it will work.

class ParamsComponent extends React.Component {
  render() {
    return (
      <div>
        <h2>Accounts</h2>
        <ul>
          <li>
            <Link to="/netflix">Netflix</Link>
          </li>
          <li>
            <Link to="/zillow-group">Zillow Group</Link>
          </li>
          <li>
            <Link to="/yahoo">Yahoo</Link>
          </li>
          <li>
            <Link to="/modus-create">Modus Create</Link>
          </li>
        </ul>
      </div>
    );
  }
}

Upvotes: 4

Related Questions