Home > Enterprise >  Toggle button highlight
Toggle button highlight

Time:01-10

I am trying to toggle a button's background color on and off, including when another button is pressed afterward. Currently, I am able to achieve this through this:

const [isActive, setIsActive] = useState(false);

  const handleClick = () => {
    setIsActive(current => !current);
  };

  return (
    <View>
      <Pressable
        style={{
          backgroundColor: isActive ? 'orange' : 'white',
        }}
        onClick={handleClick}
      >
        <Text style={{color: isActive ? 'white' : 'black'}}>Hello world</Text>
      </Pressable>
    </View>
  );
}

But the issue I get is when I click one button they all respond, changing all backgrounds and font colors, then clicking again reverts them all. how would I change this to highlight only the button selected, and then toggle off if another button is selected?

Thank you!

CodePudding user response:

All buttons respond to the same state value, so this is expected. Make a state value for each button, or create a Button component with the state value in it.

CodePudding user response:

You have to do something like that:

    const [buttonState, setButtonState] = useState({})

    .....


    const toggleButton = (id) => {
        if(buttonState[id]){
            const state = buttonState
            delete state[id]
            setButtonState(state)
        }else{
            const state = buttonState
            state[id] = true
            setButtonState(state)
        }
    }

    .......
    
    return(
        .......
        <Pressable
          style={{
            backgroundColor: buttonState[id]? 'orange' : 'white',
          }}
          onClick={()=> handleClick(id)}
        >
            <Text style={{color: buttonState[id] ? 'white' : 'black'}}>Hello world</Text>
        </Pressable>
    )

Where id is the id of button.

OR

You can do it using useRef

  • Related