Search code examples
reactjsreact-nativecomponentsreact-props

how to pass the results of a function from one component to another in react-native?


I have a component that runs a function and returns a result but I need the rest of my components to access that data from the function. How would I be able to do that?

Here is my app.js that contains the components. This is an example but my question is how would I run a function in Camera component and then reference the data in the Display component.

  export default class App extends React.Component {

  render() {
    return (
            <View>
              <Camera />
            </View>
            <View>
              <Display />
            </View>

    );
  }
}

Solution

  • You can store the data as a state in the parent component and pass it as a prop to Display, and allow Camera to alter the state through a callback (setData in the example below).

    export default class App extends React.Component {
      state = {
        data: null,
      };
      render() {
        return (
          <View>
            <View>
              <Camera setData={(data) => this.setState({ data })} />
            </View>
            <View>
              <Display data={this.state.data} />
            </View>
          </View>
        );
      }
    }
    
    const Camera = props => <Button onPress={() => props.setData(...)} />
    const Display = props => <Text>{props.data}</Text>