0

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}>
    );

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I've did that, but Page still doesn't render. I also have a similar link in Page that doesn't use a param, but that doesn't render either.
can you also add your App.jsx?
What could have happened is you didn't wrap the whole thing with Router (e.g. BrowserRouter), which is needed.

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.