1

I am trying to make it so when I click the elements I dynamically create below, they will change color.

  handleBuild() {
    const from = parseInt(document.getElementById("from").value);
    const to = parseInt(document.getElementById("to").value);
    let newSquares = [];
    for (let i = from; i <= to; i = i + 0.5) {
      if (i.toString().includes(".")) {
        newSquares.push(i.toString().split(".", 1) + ":30");
      } else {
        newSquares.push(i.toString());
      }
    }
    this.setState({ squares: newSquares });
  }

  render() {
    const items = this.state.squares.map((item) => (
      <div
        name={item}
        onClick={() => this.handleColor}
        className="squares"
        key={item}
      >
        <h4>{item}</h4>
      </div>
    ));

I am wondering how my handleColor function should look? I have a state which I can use to change the color, but first I want to know how to change the color of a dynamically created DIV in react? What info should I pass to the function to select that DIV and alter its style properties when clicked?

Thanks in advance

1 Answer 1

4

You need to pass the index of the array's element to identify the element in array. In handleColor function extract that item from array and update based on index and update the state.

handleColor = (index) => {
  const squares = this.state.squares
  const item = this.state.squares[index]
  item.color = "#fff" // any random color
  squares[index] = item
  this.setState({
    squares
   })

const items = this.state.squares.map((item,index) => (
  <div
    name={item}
    style={{ color: item.color}}
    onClick={(index) => this.handleColor(index)}
    className="squares"
    key={item}
  >
    <h4>{item}</h4>
  </div>
));
Sign up to request clarification or add additional context in comments.

2 Comments

I have tried for ages and I'm going to give up. Can you tell me what I need to research to learn about rendering DIV's dynamically and then accessing those DIV's later? Thanks
Practice make you perfect. Don't give up. With time you will get mastery. In case stuck somewhere put effort from your side if not getting result just post on stackoverflow, community help you to identify issue. you can watch maxmillian or other youtuber react youtube channel.

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.