0

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>
   )
}

1 Answer 1

2

You can use a useState hook to store your array and update it like this:

const [names, setNames] = React.useState([{ name: 'Bob', age: 20, disabled: false }, { name: 'Lisa', age: 26, disabled: false }, { name: 'Tom', age: 24, disabled: false }])

const btn = (item, index) => {
    const arr = [...names]
    for(let i = 0; i < arr.length;i++){
        arr[i].disabled = false
    }
    arr[index].disabled = true
    setClickedName(item.name)
    setNames(arr)
};

const App = () => {
    return (
        <View>
            {names.map((item, index) => {
                <Button style={styles.btn} disabledStyle={styles.btnD} disabled={item.disabled} onPress={() => btn(item, index)} />
            })}
            <Text>{clickedName}</Text>
        </View>
    )
}
Sign up to request clarification or add additional context in comments.

1 Comment

I'm sorry, I just got the chance to finally test this, and this was the solution! It works perfectly. Thank you for your help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.