If I'm mapping an array and each should be a button, how would I design the onPress function, since the amount of buttons will vary depending on the user?
I currently have 3 buttons using react native elements where each has a regular style, a disabled style and the disabled prop (true or false). I have 3 states (false as inital state) one for each button. Each button has an onPress, which sets each state. True for the one I pressed, false for the rest. How can I apply this to a unknown number of buttons?
Current code:
//fetched data:
const names : [{name: Bob, age: 20},{name: Lisa, age: 26}, {name: Tom, age: 24}, ...];
const [button1, setButton1] = useState(false);
const [button2, setButton2] = useState(false);
const [button3, setButton3] = useState(false);
const [clickedName, setClickedName] = useState("");
const btn1sel = () => {
setButton1(true);
setButton2(false);
setButton3(false);
setClickedName("Bob");
};
const btn2sel = () => {
setButton1(false);
setButton2(true);
setButton3(false);
setClickedName("Lisa");
};
const btn3sel = () => {
setButton1(false);
setButton2(false);
setButton3(true);
setClickedName("Tom");
};
const App = () => {
return(
<View>
<Button style={styles.btn} disabledStyle={styles.btnD} disabled={button1} onPress={btn1sel1} />
<Button style={styles.btn} disabledStyle={styles.btnD} disabled={button2} onPress={btn1sel2} />
<Button style={styles.btn} disabledStyle={styles.btnD} disabled={button3} onPress={btn1sel3} />
<Text>{clickedName}</Text>
</View>
)
}