skip to Main Content

I am currently trying to make an app with React Native but I am facing a problem that i don’t understand.

I want to get the id of the element the user touched, I try to do this using a onPress in a

      tasks.map(element => {
        return (
          <TouchableOpacity onPress={(element) => getTouchedId(element)}>
             <Note text={element.text} color={element.color} setpositionX={setpositionX} setpositionY={setpositionY}/>
          </TouchableOpacity>
        )
      })}

So onPress call getTouchedId and pass element as a parameter.

Here is my getTouchedId function :

  const getTouchedId = (element) => {
    console.log("element.id : " + element.id)
    settouchedId(element.id)
  }

So here you can see my function, I dont understand why I am never seeing my console.log("element.id : " + element.id) I think the problem is that my function is never red and I don’t understand why (the value of touchedId with settouchedId also never changes).

3

Answers


  1. Change onPress={(element) => getTouchedId(element)} to

    onPress={() => getTouchedId(element)}.

    The reason is element here onPress={(element) is representing the event originating on pressing but the not the element from the array

    DEMO

    Login or Signup to reply.
  2. Are you sure onPress function has element parameter?

    onPress defined like

    ({ nativeEvent: PressEvent }) => void
    

    PressEvent defined like

    {
        changedTouches: [PressEvent],
        identifier: 1,
        locationX: 8,
        locationY: 4.5,
        pageX: 24,
        pageY: 49.5,
        target: 1127,
        timestamp: 85131876.58868201,
        touches: []
    }
    
    Login or Signup to reply.
  3. Just try this.

    tasks.map((element, index) => {
            return (
              <TouchableOpacity key={index} onPress={() => getTouchedId(element, index)}>
                 <Note text={element.text} color={element.color} setpositionX={setpositionX} setpositionY={setpositionY}/>
              </TouchableOpacity>
            )
          })}
    

    I hope it will be helpful.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search