Henrik Hollósi
Henrik Hollósi

Reputation: 223

Why does my React component not render when using React-Router?

I've set up my React router in App.js. Pages component do render. When I click on a link, then the Page component won't render, but the URL in the browser changes to "page/{id}". Why is this?

Pages component:

function Pages(props) {   const managedPages = JSON.parse(localStorage.getItem("managedPages"));   console.log(managedPages);

  return (
    <div>
      <List>
        {managedPages.map(page => (
          <ListItem key={page.id}>
            <Link
              to={`/page/${page.id}`}
              style={{ textDecoration: "none", color: "black" }}
            >
              <ListItemText primary="Teszt Színház" />
            </Link>
          </ListItem>
        ))}
      </List>
      <Route path="/page" component={Page} />
    </div>   ); }

App.js jsx:

 return (
<MuiPickersUtilsProvider utils={MomentUtils}>
        <BrowserRouter>
          <div className="App">
            <BarAndMenu
              userLoginAndDataDownloadCompletedOut={
                this.userLoginAndDataDownloadCompletedOut
              }
            />
          </div>
          <Switch>
            <Route path="/" exact component={OngoingEventList} />
            <Route path="/selectSeat" component={SelectSeat} />
            <Route path="/releasePurpose/:id" component={ReleasePurpose} />
            <Route
              path="/marketingResourceConfigurationAndResult/:id"
              component={MarketingResourceConfigurationAndResult}
            />
            <Route path="/myTickets" exact component={MyTicketList} />
            <Route path="/myTickets/:id" component={MyTicket} />
            <Route path="/auditoriumList/:id" component={AuditoriumSelector} />
            <Route path="/pages" component={Pages} />
          </Switch>
        </BrowserRouter>
</MuiPickersUtilsProvider utils={MomentUtils}>
    );

Upvotes: 0

Views: 822

Answers (1)

technophyle
technophyle

Reputation: 9118

It's because /page/:id and /page are two different patterns, and they don't match.

Change your Route definition to something like this:

<Route path="/page/:id" component={Page} />

Also, you defined /page route inside /pages route, which is not rendered as soon as you navigate to /page:id. So, pull the route definition out of Pages component, and it should work.

https://reacttraining.com/react-router/web/example/url-params

Upvotes: 1

Related Questions