skip to Main Content

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

How to know which button was clicked?

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>

Thanks in advance.

2

Answers


  1. 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>
    
    Login or Signup to reply.
  2. 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>
    
        )
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search