React expand and collapse only one panel

Need help responding ... Trying to implement a collapsible list of weather weather maps. The expansion and anti-aliasing behavior is already implemented, but when I clicked on one panel, the other panel opens simultaneously (I have 2 panels and you need 7 to display the weahter for 7 days of the week).

How can I open and close only one panel?

the code:

import React, { Component } from 'react';
import Moment from 'react-moment';

import RandomGif from './RandomGif.js';

const urlForCity = city => `https://cors-anywhere.herokuapp.com/http://api.openweathermap.org/data/2.5/forecast/daily?q=${city}&units=metric&cnt=7&appid=1fba7c3eaa869008374898c6a606fe3e`

class OpenWapi extends Component {
  constructor(props) {
    super(props);
    this.state = {
      requestFailed: false,
      shown: false
    }
    this.componentDidMount = this.componentDidMount.bind(this);
    this.toggle = this.toggle.bind(this);
  }

  componentDidMount() {
    fetch(urlForCity(this.props.city))
      .then(response => {
        if(!response.ok) {
          throw Error("Network request failed")
        }
        return response;
      })
      .then(data => data.json())
      .then(data => {
        this.setState({
          weatherData: data
        })
      }, () => {
        this.setState({
          requestFailed: true
        })
      })
  }

  toggle() {
        this.setState({
            shown: !this.state.shown
        });
    }

  render() {

    if(this.state.requestFailed) return <p>Request Failed.</p>;
    if(!this.state.weatherData) return <p>Loading...</p>;

    return (
      <div>
        <p>City: {this.state.weatherData.city.name}</p>

        {/* Day 1 */}
        <div onClick={this.toggle} className="dayWeekItem">
          <div className="top-content">
            <div className="icon-weather"></div>
            <div className="date">
              <div className="weekday">Today</div>
              <div className="day-long"><Moment unix format="MMM DD YYYY">{this.state.weatherData.list[0].dt}</Moment></div>
            </div>
            <div className="temperature">
              <div className="temp-high">{parseInt(this.state.weatherData.list[0].temp.max)}ยบ</div>
              <div className="temp-low">{parseInt(this.state.weatherData.list[0].temp.min)}ยบ</div>
            </div>
          </div>
          <div className={this.state.shown ? "toggleContent-open" : "toggleContent-closed"} >
            <div className="weather-gif" >
              <RandomGif keyword={this.state.weatherData.list[0].weather[0].description} />
            </div>
          </div>
        </div>



        {/* Day 2 */}
        <div onClick={this.toggle} className="dayWeekItem">
          <div className="top-content">
            <div className="icon-weather"></div>
            <div className="date">
              <div className="weekday">Tomorrow</div>
              <div className="day-long"><Moment unix format="MMM DD YYYY">{this.state.weatherData.list[1].dt}</Moment></div>
            </div>
            <div className="temperature">
              <div className="temp-high">{parseInt(this.state.weatherData.list[1].temp.max)}ยบ</div>
              <div className="temp-low">{parseInt(this.state.weatherData.list[1].temp.min)}ยบ</div>
            </div>
          </div>
          <div className={this.state.shown ? "toggleContent-open" : "toggleContent-closed"} >
            <div className="weather-gif" >
              <RandomGif keyword={this.state.weatherData.list[1].weather[0].description} />
            </div>
          </div>
        </div>

        {/* Day 3 */}


        {/* Day 4 */}


        {/* Day 5 */}


      </div>
    )
  }
}

export default OpenWapi;
+4
source share
2 answers

I will have an object to represent the state, fields for each panel.

Like this:

constructor(props) {
    ...
    this.state = {
      requestFailed: false,
      shown: {}
    }
    ...
}

...

toggle(panelNumber) {
   this.setState({
        shown: {
            ...this.state.shown,
            [panelNumber]: !this.state.shown[panelNumber]
        }
    });
}

...

The Google function is used like Day 1:

<div onClick={() => this.toggle(1)} className="dayWeekItem">
    ...
</div>

And to show in html, for example, Day 1:

      <div className={this.state.shown[1] ? "toggleContent-open" : "toggleContent-closed"} >
        <div className="weather-gif" >
          <RandomGif keyword={this.state.weatherData.list[0].weather[0].description} />
        </div>
      </div>
+1
source

They will all always fall apart with your implementation.

state = {
  shown: true
}

.

toggle = () => {
   this.setState(shown: !this.state.shown)
}

, this.state.shown , true false

render() {
    return(<div .....//something>
        <div onClick={this.toggle}>
           { this.state.shown ? <SomeComponent or HTML Tag> : null }
        </div>
        <div onClick={this.toggle}>
          { this.state.shown ? <SomeComponent or HTML Tag> : null }
        </div>
    </div>)
}

, , , render , , div s get the same Boolean`. .

, , :

, : 1. , true false. 2. , , , .

,

 class WeatherWidget extends React.PureComponent {
   state= {
     shown: true
   }     
   toggle = () => this.setState({shown: !this.state.shown})
   render() {
       return(
         <div onClick={this.toggle} className="dayWeekItem">
            <div className="top-content">
            <div className="icon-weather"></div>
            <div className="date">
              <div className="weekday">Today</div>
              <div className="day-long">
                    <Moment unix format="MMM DD YYYY">{this.props.date}</Moment>
              </div>
            </div>
            <div className="temperature">
              <div className="temp-high">{parseInt(this.props.maxTemp)}ยบ
              </div>
              <div className="temp-low">{parseInt(this.props.minTemp)}ยบ
              </div>
            </div>
         </div>
             <div className={this.state.shown ? "toggleContent-open" : "toggleContent-closed"} >
                 <div className="weather-gif" >
                    <RandomGif keyword={this.props.gifDescription} />
                 </div>
              </div>
     </div>
       )
   }


 }

, , (React Paradigm/Composition )

class OpenWapi extends Component {
   constructor(props) {
      super(props);
      this.state = {
        requestFailed: false,
        shown: false
      }
      this.componentDidMount = this.componentDidMount.bind(this);
      this.toggle = this.toggle.bind(this);
    }

    componentDidMount() {
      fetch(urlForCity(this.props.city))
      .then(response => {
      if(!response.ok) {
         throw Error("Network request failed")
      }
      return response;
     })
     .then(data => data.json())
     .then(data => {
     this.setState({
        weatherData: data
       })
     }, () => {
       this.setState({
         requestFailed: true
     })
  })
}
render() {
    if(this.state.requestFailed) return <p>Request Failed.</p>;
    if(!this.state.weatherData) return <p>Loading...</p>;

    return(
    <div>
       <p>City: {this.state.weatherData.city.name}</p>
       <WeatherWidget 
          date={this.state.weatherData.list[0].dt}
          maxTemp={this.state.weatherData.list[0].temp.max}
          minTemp={this.state.weatherData.list[0].temp.min}
          gifDescription=
                {this.state.weatherData.list[0].weather[1].description}

       />
       <WeatherWidget 
          date={this.state.weatherData.list[1].dt}
          maxTemp={this.state.weatherData.list[1].temp.max}
          minTemp={this.state.weatherData.list[1].temp.min}
          gifDescription=
                {this.state.weatherData.list[1].weather[1].description}

       />
    </div>
    )
} 

, .

+2

Source: https://habr.com/ru/post/1691476/


All Articles