Home > Mobile >  What is the best best way to make one Pressable's text color change out of three <Pressable/
What is the best best way to make one Pressable's text color change out of three <Pressable/

Time:06-14

I am all new to React Native, and trying to understand how to make one pressable JSX element active (Active means the text colour change/Icon colour change) when the user clicks it (Any of the three Pressables)

Example: Consider I have three pressables as below

<Pressable>
    <Text><Icon name="flame" size={13} color={GRAY} /> 123</Text>
</Pressable>
<Pressable>
    <Text><Icon name="flame" size={13} color={GRAY} /> 456</Text>
</Pressable>
<Pressable>
    <Text><Icon name="flame" size={13} color={GRAY} /> 789</Text>
</Pressable>

Now I am looking for a solution that can change the user clicked pressable's ICON colour change to RED, using the best possible way.

Note: I am going to render something based on these button clicks, so looking for a best possible dynamic solution.

Thank you.

CodePudding user response:

An example for one button:

// Here we keep track of button state. Initial value is false.
const [isButtonActive, setButtonActive] = useState(false)

// On button press, set state to be the opposite of current value.
const onPressButton = () => setButtonActive((isButtonActive) => !isButtonActive)

return (
    <Pressable onPress={onPressButton}>
        <Text><Icon name="flame" size={13} color={isButtonActive ? 'red' : 'gray'} />123</Text>
    </Pressable>
)

Similarly, you can define state for all of the buttons and use the values to conditionally render components.

  • Related