Home > OS >  How to know which button was clicked, in React Native?
How to know which button was clicked, in React Native?

Time:10-18

First, I am from Web World(ReactJS), so not familier in React Native.

Now, let see the below example,

const [titleOne, setTitleOne] = useState('A button 1');
const [titleTwo, setTitleTwo] = useState('A button 2');

const handlePress=(event)=>{
    /*
        if first button clicked,
        I want to write: setTitleOne(Button 1 clicked);
        
        if second button clicked,
        I want to write: setTitleTwo(Button 2 clicked);
    */
}

<View>
  <Button title={titleOne} onPress={handlePress} />
  <Button title={titleTwo} onPress={handlePress} />
</View>

How to know which button was clicked?

Thanks in advance.

CodePudding user response:

By passing an extra arg say name ...

const [titleOne, setTitleOne] = useState('A button 1');
const [titleTwo, setTitleTwo] = useState('A button 2');

const handlePress=(event, btnName)=>{
    if(btnName === "one"){
       setTitleOne("Button 1 clicked");
    }
    if(btnName === "two"){
       setTitleTwo("Button 2 clicked");
    }
}

<View>
  <Button title={titleOne} onPress={(e)=>handlePress(e,"one")} />
  <Button title={titleTwo} onPress={(e)=>handlePress(e,"two")} />
</View>

CodePudding user response:

const App = () => {

    const [titleOne, setTitleOne] = useState('A button 1');
    const [titleTwo, setTitleTwo] = useState('A button 2');

    const handlePress = (event) => {
        if (event == 1) {
            setTitleOne("Button 1 clicked")
        } else {
            setTitleTwo("Button 2 clicked")
        }
    }

    return (
        <View>
            <Button title={"titleOne"} onPress={() => handlePress(1)} />
            <Button title={"titleTwo"} onPress={() => handlePress(2)} />
        </View>

    )
}

  • Related