Home > Blockchain >  Chnage the color of button once selected and deselect the selected button if 2nd button is selected
Chnage the color of button once selected and deselect the selected button if 2nd button is selected

Time:04-09

const renderitem = () => {
    return (
      <TouchableHighlight
        onPress={props.onClick}
      >
       <Text>{props.title}</Text>
      </TouchableHighlight>
    );
  };

I am creating a function to render a button in Flatlist, there can be multiple button based on the data in flatlist now when I select one button I want to change the color of the selected button and when I select another button then I want to deselect the 1st button which was selected and also change the color of 1st button to origin color and now change the color of the 2nd button as it has been currently selected, please let me know how I can achieve this.

CodePudding user response:

Please use state variable as style color. e.g. style={color:buttonColor1}

CodePudding user response:

const App = () => {
  const [options, setOptions] = useState<string[]>(['One', 'Two', 'Three'])
  const [selected, setSelected] = useState('One')

  const Item = ({ item, index }) => (
    <Pressable onPress={() => setSelected(item)}>
      <Text style={{ color: selected === item ? '#ff00ff' : '#000000' }}>
        {item}
      </Text>
    </Pressable>
  )

  return (
    <FlatList
      data={options}
      renderItem={Item}
    />
  )
}
  • Related