skip to Main Content

I got a list with 2 react components and their initial color is black.

The objective is next , when I click on a component I want to set the state of the previous on black if it is orange.
I tried with useState hook but I didn’t have much success.
If someone could give me some hints it will be perfect.

const Square = () => {

const [actualColor, setColor] = useState("black") 
const onClickEnterHandler = () => setColor("orange")

return(
    <div>
    </div>
    )
}

export default Square

2

Answers


  1. If you want to change multiple components, you have to move your state to their common parent and pass the state as prop or use React Context.

    const Parent = () => {
       const [color, setColor] = useState('black')
       const changeColor = () => setColor("orange")
       return (
         <>
           <Square color={color} changeColor={changeColor} />
           <Square color={color} changeColor={changeColor} />
         </>
    )}
    
    
    const Square = ({color, changeColor}) => {
    
      return(
        <div onClick={changeColor} style={{color: color}}>
          content
        </div>
      )
    }
    
    Login or Signup to reply.
  2. IF I got it correctly, when clicking on square 2, you want square 1 to be black and square 2 (currently active square) to be orange.

    If so, then try:

    const Parent = () => {
      const [activeIndex, setActiveIndex] = useState(null);
    
      // Callback function to be passed down to Square component
      const onSquareClick = (index) => {
        setActiveIndex(index);
      };
    
      const myTwoSquares = [0, 1].map((i) => (
        <Square
          index={i}
          active={i === activeIndex} // This is important
          onClick={onSquareClick}
          key={i}
        />
      ));
    
      return <div>{myTwoSquares}</div>;
    

    Then in your Square component, you can conditionally check the active prop and set the active Square to orange.

    const Square = ({ index, active, onClick }) => {
      const actualColor = active ? "orange" : "black";
      const onSquareClick = () => {
        onClick(index);
      };
    return (
        <div
         onClick={onSquareClick}
         style={{ backgroundColor: actualColor}}
        ></div>  );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search