1

I need to do a collapsible section with a list of disciplines. The disciplines are stored in an array. I wrote an onClick event but except one discipline which I clicked, I get all of them slid down. How can I apply the event to each element, so I can decide which one will be slide down?

export default class Predictions extends React.Component {
constructor(props){
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.state={
        display: 'block',
    };
}
handleClick(e) {

    this.setState({
        display: this.state.display === 'none' ? 'block' : 'none',
    });
    console.log('click', e);
};
render() {
    return (
        <section className="l-section c-predictions" >
            <h2 className="header" >Predictions</h2>
            <div className="content">
                {this.props.disciplines.map((discipline, index) => {

                    return (
                        <div onClick={event => this.handleClick(discipline.id, event)} key={discipline.name} className="c-discipline">
                            <span className="name">{discipline.name}</span> - <span className="score">{disciplineScore(this.props.athlete.skillset, discipline.requirements)}</span>
                            <div style={this.state} className="element">
                            <p>{discipline.tags !== undefined ? discipline.tags.toString().replace(',', ', ') : ''}</p>
                            <p className="isIndividual">{discipline.isIndividual===true ? "Individual sport" : "Team sport"}</p>
                            <img src={discipline.photo}/>
                            </div>
                        </div>
                    )
                })}
            </div>
        </section>
    )
}

}

1 Answer 1

3

You need a way to identify which element has been clicked.

Here's an example:

export default class App extends React.Component {
  state = {
    opened: true,
    selected: ''
  };

  toggleHidden = key => {
    this.setState({ opened: !this.state.opened, selected: key });
  };

  render() {
    return (
      <div>
        {arr.map((s, i) => (
          <div key={i}>
            <p>{s}</p>
            <button onClick={() => this.toggleHidden(i)}>Toggle</button>
            {!this.state.opened && this.state.selected === i && <h1>{s}</h1>}
          </div>
        ))}
      </div>
    );
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Great. Enjoy :)
Hi, but doesnt this use the index as the key which is not recommended.

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.