0

I have single button and a list of items. When I click the button I am trying to add a class to just the third object in the list. Can I set a class to a specific ID or a child?

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [],
      bgColor: ''
    }
  }

  jumpTo(e) {

    // item = this.state.items[2];
    //this.setState({ bgColor: 'blue' });
  }

  componentDidMount() {
    axios.get('https://api.spacexdata.com/v2/launches')
      .then((response) => {
        //console.log(response.data)
        this.setState({
          items: response.data
        })
      })
      .catch((err) => {
        console.log('Error:', err);
      })
  }

  render() {
    const List = this.state.items.map((b, i) =>
      <li key={i} id={'fn' + i}> Flight Number: {b.flight_number} and Mission_name: {b.mission_name}</li>
    );
    return (
      <div>
        <button onClick={this.jumpTo.bind(this)}></button>
        <ul>
          {List}
        </ul>
      </div>
    );
  }
}

render(<App />, document.getElementById("root"));

1 Answer 1

2

id={'fn' + i} you can use this if you want to do in simple way

jumpTo(e) 
{
    document.getElementById("fn2").classList.add("classname");
}

or you can do in this way also

 jumpTo(e) {
     const rawItem = this.state.items;
     rawItem[2].classes = "classname";
     this.setState({ items: rawItem });
  }

render() {
    const List = this.state.items.map((b, i) =>
      <li key={i} id={'fn' + i} className={b.classes?b.classes:""}> Flight Number: {b.flight_number} and Mission_name: {b.mission_name}</li>
    );
Sign up to request clarification or add additional context in comments.

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.