skip to Main Content

In web React I can do something like this:

const handleClick = ({ target: { dataset } }) => 
{
    const buttonValue = dataset.somevalue;
}

return (
  <div>
    <button data-somevalue="value1" onClick={handleClick}>
        ButtonText
    </button>

    <button data-somevalue="value2" onClick={handleClick}>
        ButtonText
    </button>
  </div>
)

or it can even done with other attributes like name.

I have tried this:

const handlePress = (value) =>
{
    console.log(value);
}

return (
    <Viev>
      <TouchableOpacity onPress={handlePress("value1")}>
          <Text>ButtonText</Text>
      </TouchableOpacity>

      <TouchableOpacity onPress={handlePress("value2")}>
          <Text>ButtonText</Text>
      </TouchableOpacity>
    </Viev>
)

But dosen’t work as expected, so how can I achieve this?

2

Answers


  1. Simple you need to pass the arrow function,Below I shared the updated code.you can try and let me know further.

          <TouchableOpacity onPress={()=>handlePress("value1")}>
              <Text>ButtonText</Text>
          </TouchableOpacity>
    
          <TouchableOpacity onPress={()=>handlePress("value2")}>
              <Text>ButtonText</Text>
          </TouchableOpacity>
    
    Login or Signup to reply.
  2. You can achieve this using the following format.

    <TouchableOpacity
      onPress={() => {
        handlePress('value1');
      }}>
      <Text>ButtonText</Text>
    </TouchableOpacity>
    
    <TouchableOpacity
      onPress={() => {
        handlePress('value2');
      }}>
      <Text>ButtonText</Text>
    </TouchableOpacity>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search