K. Smith
K. Smith

Reputation: 65

ReactJS - How to style a <td> tag when working with arrays?

I have a Table React component that renders the following table. This Table class receives a prop called array which let's say has 10 elements in it. So I am basically going through the array and adding every element to a new row. What I want to do is when a user clicks a particular button in the app, the column with id foo should turn yellow.

class Table extends React.Component {
  render() {
    return (
      <table>
          <thead>
            <tr><th>Heading 1</th></tr>
          </thead>
          <tbody>
            {this.props.array.map(element =>
              <tr key={element}>
                <td id="foo">{element}</td>
              </tr>
            )}
          </tbody>
      </table>
    );
  }
}

Right now, I am trying to do something like this:

class Bar extends React.Component {
  row;

  componentDidMount() {
    this.row = document.getElementById("foo");
  }

  render() {
    return {
      <button onClick={(event) => {
        this.update();
      }}>I will turn the #foo column yellow!
      </button>
    }
  }

  update() {
    this.row.classList.add('yellow-color');
  }
}

CSS:

.yellow-color {
  background-color: yellow;
}

However, it does not turn that column yellow. Does anyone know why this is the case? How do I go about with this problem? Thanks!

Upvotes: 0

Views: 6778

Answers (1)

Ryan C
Ryan C

Reputation: 426

You shouldn't be using document.getElementById() in React. You can achieve similar with Refs, although it is not recommended.

You can achieve the same with using state and passing props.

class Table extends React.Component {
  state = {
    color: "black"
  };
  update = () => {
    this.setState({
      color: "yellow"
    })
  }
  render() {
    return (
      <div>
      <button onClick={(event) => {
        this.update();
      }}>I will turn the #foo column yellow!
      </button>
      <table>
          <thead>
            <tr><th>Heading 1</th></tr>
          </thead>
          <tbody>
            {this.props.array.map(element =>
              <tr key={element}>
                <td style={{ backgroundColor: this.state.color }}>
                  {element}
                </td>
              </tr>
            )}
          </tbody>
      </table>
      </div>
    );
  }
}

Upvotes: 3

Related Questions