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:

export default function App() {
  const [screen, setScreen] = useState(0);

  const setScreenState = () => { //I want to be able to pass an argument into here so that i can set the screen that is shown with my switch statement.
    console.log("setting screen");
  };

  switch (screen) {
    case 0:
      return <WelcomeScreen setScreen={setScreenState} />;
      break;
    case 1:
      return <ViewImageScreen setScreen={setScreenState} />;
      break;
    case 2:
      return <ViewHelp setScreen={setScreenState} />;
      break;
  }
}

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:

function WelcomeScreen(props){
  // you can invoke here if you want
  props.setScreen('my value');

  // or you can invoke in an event
  return (<button onClick={e=> props.setScreen('my value')}>Click me!</button>);
}

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.

return <WelcomeScreen setScreen={()=> setScreenState('parameter i want to set')} />

or using .bind

return <WelcomeScreen setScreen={setScreenState.bind(null, 'parameter i want to set')} />

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:

const setScreenState = (myArg) => { 
    console.log("setting screen: " + myArg);
};
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement