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>
        );
      }
    });
  }
}
1

2 Answers 2

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
  }
});
Sign up to request clarification or add additional context in comments.

Comments

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>
      );
    }
  });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.