Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React native parent child communication and return values

I am a beginner to the react native environment. I want to understand parent child communication in react native.

  1. Parent will pass a number to a child - As an example parent pass "2" to a child.

  2. Child will have a processing function which multiple the same number 2 times and return the result back to parent. - As example 2*2 and return

  3. parent will call child function and see if output if correct and print results on parent container

  4. if I would have done this in a programming lang like c++ or java.

    *

parent.number = 2;
  parent.result = child.getResult(parent.number);
  if(parent.result == 4){
      Print "child return correct value";
  }else{
      child return wrong value.
  }

*

I have seen couple of react native tutorials online but, still this parent child communication is not clear.

Can someone please code 2 react native js file one for parent and one for a child and show me the communication.

Thanks

like image 381
Tajinder Singh Avatar asked Dec 14 '16 16:12

Tajinder Singh


1 Answers

It is done by passing callbacks/handlers to child component, here is an example. I have not tested it though.

Parent.js

import React, { Component } from 'react';
import { Text, View } from 'react-native';
import Child from './Child.js';

export default class Parent extends Component {
    constructor() {
        super();
        this.state = {
            result: 0
        };
    }

    getResponse(result){
        this.setState({result});
    }

    render(){
        return (
            <View>
                <Text>{this.state.result}</Text>
                <Child num={2} callback={this.getResponse.bind(this)}>
            </View>
        );
    }
}

Child.js

import React, { Component } from 'react';
import { Button } from 'react-native';

export default class Child extends Component {
    calc(){
        this.props.callback(this.props.num * 2);
    }

    render(){
        return (<Button onPress={() => this.calc()} title="Calc" />)
    }
}

These are some recommended readings to understand better react https://facebook.github.io/react/docs/thinking-in-react.html https://facebook.github.io/react/docs/lifting-state-up.html

like image 54
diedu Avatar answered Oct 19 '22 16:10

diedu