1

I am trying to generate components from a JSON file with React-Native, and am wondering what is the best way to pass a function to a component as a prop?

Example, button requires the prop onPress, so is there a way to pass in a function to the object onPress as I have done here:

{
      component: "Button",
      props: {
            title: "This is the Title",
            onPress: {() => {Alert.alert("Tapped!")}}
      }
}

As this generates an unexpected token error, what is a better way to accomplish this?

0

1 Answer 1

3

You have extra curly brackets around the function declaration that are invalid. Remove those, and you should be good:

{
      component: "Button",
      props: {
            title: "This is the Title",
            onPress: () => {Alert.alert("Tapped!")}
      }
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for your answer. It seems that this does allow this function to be called, but the "Alert" component is not available as it was called from the data file. Is there a way around this?
Have you imported or required Alert in the file where it's being called?
Yes, but the stack trace shows that the function is being called in the data.json file that currently holds the dummy data. Any ideas?
Can you change the JSON file to a .js file, and export your config object? Then, perhaps if the import/require of {Alert} is declared in the file where the alert function is defined, it will carry over.
I will try that. Eventually, I plan to serve the file remotely. In that case would it even be possible to have the file "export" itself as you recommended?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.