Home > OS >  Onpress is not calling the function to change the state
Onpress is not calling the function to change the state

Time:01-10

I am using React Native.I am trying to change the button when it is clicked. I want to show the add item component by default and when it is clicked I want it to change to remove item.

const Products = () => {
const [added,notAdd]=useState(false);
 function changeIT(){
        console.log(added);
        notAdd(!added);
        console.log(added);
        
    }
return (
{added?<Remove index={index} onPress={()=>changeIT()}/> :<Add item={item} onPress={()=>changeIT()}/> }
)}

Nothing happens after I click on the buttons.

CodePudding user response:

I believe you have only included the onPress event when the component is being executed, not in the actual component itself, for example.

Execution:

<Add item={item} onPress={()=>changeIT()}/>

Declaration:

import React, {useState} from 'react';
import { Pressable, Text} from 'react-native';

export default function Add({ item , onPress}) {

  return (
    <Pressable onPress={onPress}> 
      <Text>Add</Text>
    </Pressable>
  );
}
  • Related