Displaying Array Of Sub-Components

Displaying Array Of Sub-Components
0

The problem I’m now having with my React weather app is a bit of a continuation from this thread.

However, while I’m able to display my currentWeather just fine and some of the forecast displays, I am having a hard time understanding how to display a 5-day forecast in the form of 5 <ForecastDayCard /> subcomponents without running into trouble.

const ForecastDayCard = (props) => null;

export default class Forecast extends React.Component {
  render() {
    let {data} = this.props;
    if(!data.city) return null;
    let city = data.city;
    const forecastDayCards = data.forecast.map(weather => <ForecastDayCard key={weather.dt_txt}/>);
    console.log(forecastDayCards);

My idea was to initialize a subcomponent, <ForecastDayCard/>, initially set to null. Then, inside render(), I would create an array of those subcomponents and store to forecastDayCards.

First, the console was telling me that each child had to have a unique key for each child (makes sense, so I decided to use weather.dt_txt since each date is unique). However, I’m still not seeing anything render even though I’m rendering forecastDayCards in a <div>.

I’m also experimenting by setting the value prop to the day’s temp (converted to Fahrenheit, rounded to one decimal).

So I know I’m creating the <ForecastDayCards/> with no problem (at least, I hope). I just can’t seem to figure out how to render the unique date along with the day’s average temperature?

Your code works as it should: since the ForecastCard renders as null, its containing div is empty, and produces nothing in the resulting html page.

Try returning some dummy html content instead, something like:

const ForecastDayCard = (props) => (<p>TODO: ForecastDayCard</p>);

So what I tried was, instead of returning an array of subcomponents with prewritten markup, I would return raw markup with the data I want to render:

    const forecastDayCards = data.forecast.map(item => (
      <div key={item.dt_txt} className={classes.card}>
        <div>
          {getDayOfWeek(item.dt_txt)}
        </div>
        <div>
          {kelvinToFahrenheit(item.main.temp).toFixed(1)}
        </div>
        <img alt="weather_icon" src={`http://openweathermap.org/img/wn/` + item.weather[0].icon + ".png"}/>
        <div>
          H: {kelvinToFahrenheit(item.main.temp_max).toFixed(1)} | L: {kelvinToFahrenheit(item.main.temp_min).toFixed(1)}
        </div>
      </div>

    ));

I’m sure there is a way to do it with subcomponents, but this turned out to produce what I needed atm.