changing styles of element(s) , not based on firing event

Viewed 31

I'm learning react and I'm editing a tutorial Tic Tac Toe game. When there is a winner, the winning line should be highlighted. I passed a line prop all the way down to the Square component and i came up with this code:

function Square(props) {
    props.line ? 
       return (
          <button className="square" onClick={props.onClick} style={{backgroundColor: "red"}}>
            {props.value}
          </button>
       );
    :
       return (
          <button className="square" onClick={props.onClick}>
            {props.value}
          </button>
       );
}

First, there is a syntax error at first return, but whenever i try to fix it, i just create a new one, clearly i don't know how to handle JavaScript inside return, then even if what i intended was a correct syntax, it probably still would change only the color of a particular Square and not the whole props.line.

1 Answers

You can handle the style in one return statement, use this:

function Square(props) {
  return (
    <button className="square" onClick={props.onClick} style={props.line ? {backgroundColor: "red"} : undefined}>
      {props.value}
    </button>
  );
}

You can take a look at this codepen for a live working example of this solution.

Related