Home > Software engineering >  Is useRef hook a good use case for changing the style of individual item than useState?
Is useRef hook a good use case for changing the style of individual item than useState?

Time:06-02

I have card that rotates on click. It works for one card however if there are multiple cards, it rotates them all on single click. while i want to rotate them individually.

I am new to useRef hook and wondering if it okay to use useRef hook to achieve this or should i break it into a separate component with its own state and pass it back to main component ?

I am more concern about the right way of achieving this.

function App() {

     const [clicked, setClicked] = useState(false);
     const handleClick = () => {
          setClicked(!clicked);
     };

   return (
      <div className={`card ${clicked ? "rotate-180" : ""}`}
        onClick={handleClick}
      ></div>
   );
}

CodePudding user response:

Try to move the button in a separate component with its own state for each button.

Anyway, the main difference between useRef and useState is that when the ref from useRef is changed, the component does not re-render, however, once the state from useState is changed, so does the component (it is re-rendered).

CodePudding user response:

I recommend storing all cards information in an array and mapping them, after that assigning a key to each card, and using that key to apply conditional styling.

here is an example :

  const [clicked, setClicked] = React.useState({state : false,buttonID:Number});
  const handleClick = (id) => {
    setClicked({state:!clicked.state,buttonID:id});
  };

  const buttons = ["a", "b", "c", "d"];


      {buttons.map((x, i) => (
        <div
          key={i}
          className={`card ${(clicked.state && clicked.buttonID===i) ? "rotate-180" : ""}`}
          onClick={()=>handleClick(i)}
        >
          {x}
        </div>

demo

  • Related