0

I am trying to understand nested react routes. My current issue is that my link outputs undefined and also renders the component on the same view instead of loading just that component view.

Events.js

const data = {
   "events":[
      {
         "id":"1234",
         "name":"Meetup",
         "description":"Tech meetup"
      },
      {
         "id":"34234",
         "name":"Test",
         "description":"Events"
      }
   ]
}

{data.events.map(event => (
    <Link to={`/events/${data.events.id}`}>
        <EventCard data={event} />
    </Link>
))}

<Switch>
  <Route path={`/events/:eventId`}  render={(props) => <Event {...props}  />}/>
</Switch>

How can I render the Event component when a user has clicked one of the event card. I can currently load both components on the same page but that is not my desired output. The expected path should be:

Expected:

Render only

Current:

Renders & on same page

Freddy.
  • 1,015
  • 1
  • 7
  • 21

2 Answers2

0

You need to add id param to your event endpoint:

 <Route path="/events/:id?" component={Event} />

Then in the Event you can check if id is present via props.match.params.id.

Clarity
  • 8,980
  • 2
  • 14
  • 29
0

At first you have got a problem here,

<Link to={`/events/${data.events.id}`}>

Since you are already mapping event object from data array, iterator event already holds event data. So you should change it like this;

<Link to={`/events/${event.id}`}>

Also I'd strongly recommend to use 'exact' prop in your routes for routing multiple endpoints from same root like this.

<Route exact path={`/events/:eventId`}  render={(props) => <Event {...props}  />}/>

See here for further information. Difference between exact path and path

alpsavrum
  • 98
  • 6
  • I think my issue is that once I click on a Card the url is events/1234 however both my Events component and Event component both render on the same page. I would like to render only Event once I click on a card – Freddy. Aug 09 '19 at 12:24
  • I did and it does work however the Events and Event component are loaded on both pages. OnClick i would like to render not . Would it an issue on the WebApp level? always rendering Events? – Freddy. Aug 09 '19 at 12:50
  • Maybe you can try using a wrapper for component such as that renders by prop. At the moment, I don't know your architecture but you can give it a shot. – alpsavrum Aug 09 '19 at 13:05