Skip to content
Advertisement

Passing arguments into props react-native?

I’m new to react and am trying to figure out how things like props work. I want to have it so I can pass a function which i know how to do but i want to do it with some argument. I know my switch statement works because if I manually set the value it works as expected. I’m just too dumb to figure it out. Here is my code:

JavaScript

This is probably a dumb question I’m just having a hard time wrapping my head around props and how the work. No matter how much I read or watch i just dont get it :(.

Advertisement

Answer

*Edit: it looked to me that the OP was asking how to “pass” both function and argument. If you actually want to call the function with an argument supplied in the child element, it’s much easier. You pass in the function just like you’re doing above, and in the child element you invoke it:

JavaScript

Original answer: if you want to set the argument in the parent element, you can do one of two things: either an arrow function, or .bind. Either will work. Then you would invoke it in the child with no argument at all, like props.setScreen()…because the argument is hard-coded in the parent.

JavaScript

or using .bind

JavaScript

Note that with .bind the first argument is the value of this, and the arguments go after that. You probably don’t need a this since you’re using functional components, so null is usually fine.

Oh, and of course you have to add your argument to your function definition:

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement