Home > Back-end >  How can I pass a value to a function when onPress is pressed in Reactnative?
How can I pass a value to a function when onPress is pressed in Reactnative?

Time:07-09

I'm using Reactnaitve When onPress is triggered, the photosModalControl function is executed and I want to get the value first, and I also want to execute setUploadPhotos. But when I use my code, I get the value, but setUploadPhotos is not executed. How do I fix the code?

this is my code

const photosModalControl = (value: string) => () =>  {
    console.log(value);
    setUploadPhotos(prevState => !prevState);
};


<Pressable 
onPress={photosModalControl("first")}
>
</Pressable>

CodePudding user response:

If im not mistaken, shouldn't you set up your function like this:

const someFunction = (variable: type) => { functions stuff}

you doubled up and put:

const someFunction = (variable: type) = () => { functions stuff}

CodePudding user response:

The way you are passing the function in the onPress will result in that function call on render. Instead use this:

    const photosModalControl = (value: string) => () =>  {
        console.log(value);
        setUploadPhotos(prevState => !prevState);
    };


    <Pressable onPress={()=>photosModalControl("first")}>Button</Pressable>

This way you can pass any number of arguments to your function

  • Related