user19476497
user19476497

Reputation: 557

How can I pass a value to a function when onPress is pressed in Reactnative?

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>

Upvotes: 1

Views: 1520

Answers (2)

Phillip Cabaniss
Phillip Cabaniss

Reputation: 1

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
}

Upvotes: 0

Puneet56
Puneet56

Reputation: 126

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

Upvotes: 1

Related Questions