Search code examples
javascriptreactjsreact-nativeecmascript-6react-native-router-flux

Sending prop and then using it as a function in React?


I am trying to send a RouteKey prop and then trying to use the prop inside a chained function.

Here is my Component:

<MenuItem RouterKey={'assetsList'} />

And inside the component definition, I am trying to use it inside the actions function like so :

    import { Actions } from 'react-native-router-flux';
    const MenuItem = (props) => {
  return (
      <TouchableWithoutFeedback onPress={() => { return `${Actions}.${props.RouterKey}()`; }}>
        <View>
         //somethings here...
        </View>
      </TouchableWithoutFeedback>
  );
};

Basically what I want to do is:

<TouchableWithoutFeedback onPress={() => { Actions.whateverWasPassed(); }}>

However, I am not able to do this. What am I missing here? I know the way I am doing it is wrong. What is the correct way to do this?


Solution

  • You can dynamically call any static method by ClassName[methodName](). It is particularly useful when you have method name as a string. (Just like your case).

    So in your case, it will be

    <TouchableWithoutFeedback onPress={() => { return Actions[props.RouterKey]();}}>
    

    Another approach that you can follow is, you can directly pass Actions.assetsList method as a prop and invoke it in your MenuItem component.

    <MenuItem scene={Actions.assetsList} />
    

    Now, In your MenuItem component, you can invoke this method as props.scene(). Both the approach will work fine.

    Here is the link to my answer on a similar question.