0

Trying to conditionally render values from an array object if isDayTime is equal to true.

Tried .filter and .map but I don't think I'm doing it properly.

    const weather = this.props.weather.weatherData;
    return weather.map(weather => {
      if (weather.isDayTime === true) {
        return (
          <div className="ui segment">
            <div className="ui center grey aligned header">TheDay</div>
            <div className="ui center grey aligned header">
              <i className="sun icon" />
            </div>
            <div className="ui center grey aligned sub header">
              Min:75° Max:80°
            </div>
          </div>
        );
      }
    });
  }
}
  • Possible duplicate of [How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/how-to-filter-object-array-based-on-attributes) – Heretic Monkey Jun 13 '19 at 20:54

2 Answers2

1

use filter on weatherData and return items that match the condition.

const weatherData = this.props.weather && this.props.weather.weatherData || [];
const weather = weatherData.filter(weather => weather.isDayTime === true);

return weather.map(weatherItem => {

    return (
      <div className="ui segment">
        <div className="ui center grey aligned header">TheDay</div>
        <div className="ui center grey aligned header">
          <i className="sun icon" />
        </div>
        <div className="ui center grey aligned sub header">
          Min:75° Max:80°
        </div>
      </div>
      );
    }
  });
}
Junius L
  • 15,881
  • 6
  • 52
  • 96
1

What you can do is

1 - Filter the data first and map the filtered data in your render.

const weather = this.props.weather.weatherData;
const weatherFiltered = weather.filter( ({ isDayTime }) => isDayTime );

return weather.map(weather => {
    return (
      <div className="ui segment">
        <div className="ui center grey aligned header">TheDay</div>
        <div className="ui center grey aligned header">
          <i className="sun icon" />
        </div>
        <div className="ui center grey aligned sub header">
          Min:75° Max:80°
        </div>
      </div>
    );
});

2 - Map in your render and return null when you don t want an item to be rendered.

return weather.map(weather => {
  if (weather.isDayTime === true) {
    return (
      <div className="ui segment">
        <div className="ui center grey aligned header">TheDay</div>
        <div className="ui center grey aligned header">
          <i className="sun icon" />
        </div>
        <div className="ui center grey aligned sub header">
          Min:75° Max:80°
        </div>
      </div>
    );
    return null
  }
});
FurkanO
  • 7,100
  • 5
  • 25
  • 36