Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

toggling individual item using map in react

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [],
      loading: true,
      clicked: null // <-- start with null state
    }
  }
  
  componentDidMount() {
    fetch('https://restcountries.eu/rest/v2/all')
      .then(response => response.json())
      .then(data => this.setState({ data }))
      .finally(() => this.setState({ loading: false }));
  }

  clickHappens = (id) => () => {
    this.setState(prevState => ({
      clicked: prevState.clicked === id ? null : id, // <-- toggle back to null or to new id
    }));
  }
  
  render() {
    return (
      <div className="container">
        {this.state.data?.map((item, id) => (
          <div
            className="box"
            key={id}
            onClick={this.clickHappens(id)} // <-- pass id to toggle
          >
            {this.state.clicked === id ? // <-- check id match
              <Countryinformation
                continent={item["subregion"]}
                language={item["languages"][0]["name"]}
              />
              :
              <Countryname name={item["name"]}/>
            }
          </div>
        ))}
      </div>
    )
  }
}
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #toggling #individual #item #map #react
ADD COMMENT
Topic
Name
9+1 =