You can make a toggle button like below and toggle the styles, Basically we set the background color and text color using the variable, and i have added a callback which you can use in your main component.
const Filters = ({ data, onValueChange }) => {
const [selectedIndex, setSelectedIndex] = useState(-1);
return (
<View style={{ flexDirection: 'row' }}>
{data.map((x, i) => (
<FilterButton
text={x.title}
id={i}
selectedIndex={selectedIndex}
callback={(id) => {
setSelectedIndex(id);
if (onValueChange) {
onValueChange(id);
}
}}
/>
))}
</View>
);
};
const FilterButton = ({ callback, text, id, selectedIndex }) => {
const clicked = selectedIndex === id;
return (
<TouchableOpacity
style={[
{ borderRadius: 20, borderColor: 'black', borderWidth: 2, padding: 10 },
{ backgroundColor: clicked ? 'black' : 'white' },
]}
onPress={() => {
callback(id);
}}>
<Text style={{ color: clicked ? 'white' : 'black' }}>
{text}
</Text>
</TouchableOpacity>
);
};
Usage
<Filters data={[{ title: 'Test' }, { title: 'test2' }]} onValueChange={(id)=>alert(id)}/>
CLICK HERE to find out more related problems solutions.