Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks in advance.

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading