React props: matching with url params

Hi,

I’m rendering a show page that takes the params from the url.
I pass down the whole props from App so I can render multiple properties of the object that matches the url.

Here, chosenCity is coming up undefined even though the props show the full array of cities is there, and the h1 and the first h2 render without a problem:

import React from "react";

const CityShow = props => {
  let chosenCity = props.cities.find(
    city => city.city === props.match.params.city
  );
  return (
    <div>
      <h1>{props.match.params.city}</h1>
      <h2>{props.cities.map(city => city.city)}</h2>
      {/* <h2>{chosenCity.city}</h2> */}
    </div>
  );
};

export default CityShow;

I can’t quite see my mistake?

Assuming that your code is correct,

apparently your cities array doesn’t have a match for the current city in the url. If find method doesn’t find it, it returns undefined.

Thanks shimphillip, the url comes from the cities’ array (from the index page) in the first place, so it is definitely there.
I assume I’m doing something wrong with .find, because .map works fine. I’ve looked at those docs, thanks.

I fixed it, the problem was conditional rendering, the cities array would be empty while waiting for the fetch. So would break the .find cause it would return undefined.