score:3

Accepted answer

enter image description here@matej, if you are looking for updates i hope this will work for you. https://codesandbox.io/s/youthful-shockley-o1dzo?file=/src/app.js

const constantweather = props => {
  return (
    <div classname="card" key={props.cityid}>
      <div>
        {props.cityname}, {props.country}
      </div>
      <div>{props.temperature}</div>
      <img alt="" />
    </div>
  );
};

const constantweatherlist = props =>
  (props.weatherconst || [])
    .filter(el => el) // filter null if you getting from api
    .map(el => {
      return (
        <constantweather
          key={el.id}
          cityid={el.id}
          cityname={el.name}
          country={el.sys.country}
          temperature={el.main.temp}
        />
      );
    });

<constantweatherlist weatherconst={data} />

// styles
.card {
  display: inline-block;
  border: 1px solid;
  padding: 10px;
  margin: 10px;
}

score:1

  1. you should add a null check in order not to take undefined error from api responses for nested objects. you need to check whether el.sys is defined or not.

  2. try to use normal classes in css. just import the css file and use strings as a classname.

  3. you must set the key to the element that comes after from map function. for this case, it should be

<constantweather key={city.id} />

score:2

to solve the 1st issue you will need to wait for the api to successfully retrieve data and then only you should map on the data. so what you could do is you set initial state for weatherconst as an empty array like below

const [weatherconst, setweatherconst] = usestate([]);

and then while mapping on the data you could check the length of the fetched data. while check you should do boolean operation not just length check.

let constantweatherlist = weatherconst.length > 0 && weatherconst.map(el => {
    return <constantweather 
              key={el.id}
              cityid={el.id} 
              cityname={el.name} 
              country={el.sys.country} 
              temperature={el.main.temp} 
              />
  })

remember, this is just an example and there are multiple ways to do the same thing.

  1. for css issue you will need to assign a proper class to the div as classname="card"

  2. for the 3rd issue you need to assign key to constantweather component as shown in the code above.


Related Query

More Query from same tag