Home > front end >  set Style using React and Hooks
set Style using React and Hooks

Time:06-13

I have been using React JS for a short time. Looking at the following example, I would like to change the background color only on the clicked lines and not all lines. Actually, clicking on a row turns it red and clicking again makes the row background white. Before changing color, I would set all lines to default color states, but something is wrong.


import { useState } from "react";

export default function App() {
  const [color, setColor] = useState("white");

  const handleClick = (e) => {

    const value_color = e.target.style.backgroundColor;

    if (value_color != "" && value_color != undefined) {
      if (value_color === "white") 
        var new_color = "red";
      else 
        var new_color = "white";
    }

    setColor("white");
    e.target.style.backgroundColor = new_color;

  };

  return (
    <div>
      <div
        id={"line1_id"}
        style={{
          backgroundColor: color
        }}
        onClick={handleClick}
      >
        First Line
      </div>

      <div
        id={"line2_id"}
        style={{
          backgroundColor: color
        }}
        onClick={handleClick}
      >
        Second Line
      </div>
    </div>
  );


}


EDIT: Maybe I have explained the problem wrong. Actually my code works, but clicking on both I get two red lines. In general, when I click on a new line, the other line should go white again. Thank you

CodePudding user response:

The new_color value is not defined because you are setting it in the if-else statements. So, only code in the if-else blocks can access them. You can declare a variable and assign a default value outside them and then reassign it:

// some other code
let new_color = "white"
if (value_color != "" && value_color != undefined) {
      if (value_color === "white") 
        new_color = "red";
      else 
        new_color = "white";
}
// some code
e.target.style.backgroundColor = new_color;

CodePudding user response:

Create JSON for the data and use map for rendering the data and updating the backgroundColor

import { useState } from 'react';

export default function App() {
  const [data, setData] = useState([
    { id: 1, text: 'First Line', color: 'white' },
    { id: 2, text: 'Second Line', color: 'white' }
  ]);
  const handleClick = item => {
    setData(data =>
      data.map(n => {
        return {
          ...n,
           color:  n.id === item.id && n.color === 'white' ? 'red' : 'white'
        };
      })
    );
  };

  return (
    <div>
      {data.map(item => (
        <div
          id={item.id}
          key={item.id}
          style={{
            backgroundColor: item.color
          }}
          onClick={() => handleClick(item)}
        >
          {item.text}
        </div>
      ))}
    </div>
  );
}

here is the Codesandbox example

  • Related