KaronatoR
KaronatoR

Reputation: 2653

ReactJS call parent method

I'm making my first step in ReactJS and trying to understand communication between parent and children. I'm making form, so I have the component for styling fields. And also I have parent component that includes field and checking it. Example:

var LoginField = React.createClass({
    render: function() {
        return (
            <MyField icon="user_icon" placeholder="Nickname" />
        );
    },
    check: function () {
        console.log ("aakmslkanslkc");
    }
})

var MyField = React.createClass({
    render: function() {
        ...
    },
    handleChange: function(event) {
        // call parent!
    }
})

Is there any way to do it. And is my logic is good in reactjs "world"? Thanks for your time.

Upvotes: 182

Views: 284911

Answers (7)

ittgung
ittgung

Reputation: 304

Parent

const parentFunction = (points: number) => {
  setCount(points)
}
return(
    <div>
    <div>
       <h2>Parent Component</h2><br/>
       {count && `Received: ${count} points from child`}
       <Child parentFunction={parentFunction}/>
    </div>
    </div>
 )
}

Child

return(
    <div style={{padding: 30}}>
      <div>
        <h3>Child Component</h3>
        <p>Send : <input value={points} onChange={(e) => setPoints(+e.target.value)}/> points to Parent</p>
        <p style={{textAlign: "center"}}><button onClick={() => props.parentFunction(points)}>Send to parent</button></p>
      </div>
  </div>
  )

Thankyou to L Raney

Upvotes: 0

Omkesh Sajjanwar
Omkesh Sajjanwar

Reputation: 863

Using Function || stateless component

Parent Component

 import React from "react";
 import ChildComponent from "./childComponent";

 export default function Parent(){

     const handleParentFun = (value) =>{
       console.log("Call to Parent Component!",value);
     }

     return (
         <>
             This is Parent Component
             <ChildComponent 
                 handleParentFun = {(value) => {
                     console.log("your value -->",value);
                     handleParentFun(value);
                 }}
             />
         </>
     );
 }

Child Component

import React from "react";


export default function ChildComponent(props){
    return(
        <> 
           This is Child Component 
           <button onClick={props.handleParentFun("Your Value")}>
               Call to Parent Component Function
           </button>
        </>
    );
}

Upvotes: 16

Fangming
Fangming

Reputation: 25260

2019 Update with react 16+ and ES6

Posting this since React.createClass is deprecated from react version 16 and the new Javascript ES6 will give you more benefits.

Parent

import React, {Component} from 'react';
import Child from './Child';
  
export default class Parent extends Component {

  es6Function = (value) => {
    console.log(value)
  }

  simplifiedFunction (value) {
    console.log(value)
  }

  render () {
  return (
    <div>
    <Child
          es6Function = {this.es6Function}
          simplifiedFunction = {this.simplifiedFunction} 
        />
    </div>
    )
  }

}

Child

import React, {Component} from 'react';

export default class Child extends Component {

  render () {
  return (
    <div>
    <h1 onClick= { () =>
            this.props.simplifiedFunction(<SomethingThatYouWantToPassIn>)
          }
        > Something</h1>
    </div>
    )
  }
}

Simplified stateless child as ES6 constant

import React from 'react';

const Child = (props) => {
  return (
    <div>
    <h1 onClick= { () =>
        props.es6Function(<SomethingThatYouWantToPassIn>)
      }
      > Something</h1>
    </div>
  )

}
export default Child;

Upvotes: 94

Sandeep Shekhawat
Sandeep Shekhawat

Reputation: 695

React 16+

Child Component

import React from 'react'

class ChildComponent extends React.Component
{
    constructor(props){
        super(props);       
    }

    render()
    {
        return <div>
            <button onClick={()=>this.props.greetChild('child')}>Call parent Component</button>
        </div>
    }
}

export default ChildComponent;

Parent Component

import React from "react";
import ChildComponent from "./childComponent";

class MasterComponent extends React.Component
{
    constructor(props)
    {
        super(props);
        this.state={
            master:'master',
            message:''
        }
        this.greetHandler=this.greetHandler.bind(this);
    }

    greetHandler(childName){
        if(typeof(childName)=='object')
        {
            this.setState({            
                message:`this is ${this.state.master}`
            });
        }
        else
        {
            this.setState({            
                message:`this is ${childName}`
            });
        }

    }

    render()
    {
        return <div>
           <p> {this.state.message}</p>
            <button onClick={this.greetHandler}>Click Me</button>
            <ChildComponent greetChild={this.greetHandler}></ChildComponent>
        </div>
    }
}
export default  MasterComponent;

Upvotes: 1

Jonca33
Jonca33

Reputation: 3493

Pass the method from Parent component down as a prop to your Child component. ie:

export default class Parent extends Component {
  state = {
    word: ''
  }

  handleCall = () => {
    this.setState({ word: 'bar' })
  }

  render() {
    const { word } = this.state
    return <Child handler={this.handleCall} word={word} />
  }
}

const Child = ({ handler, word }) => (
<span onClick={handler}>Foo{word}</span>
)

Upvotes: 3

Vitalii Andrusishyn
Vitalii Andrusishyn

Reputation: 4172

You can use any parent methods. For this you should to send this methods from you parent to you child like any simple value. And you can use many methods from the parent at one time. For example:

var Parent = React.createClass({
    someMethod: function(value) {
        console.log("value from child", value)
    },
    someMethod2: function(value) {
        console.log("second method used", value)
    },
    render: function() {
      return (<Child someMethod={this.someMethod} someMethod2={this.someMethod2} />);
    }
});

And use it into the Child like this (for any actions or into any child methods):

var Child = React.createClass({
    getInitialState: function() {
      return {
        value: 'bar'
      }
    },
    render: function() {
      return (<input type="text" value={this.state.value} onClick={this.props.someMethod} onChange={this.props.someMethod2} />);
    }
});

Upvotes: 57

Mike Driver
Mike Driver

Reputation: 8511

To do this you pass a callback as a property down to the child from the parent.

For example:

var Parent = React.createClass({

    getInitialState: function() {
        return {
            value: 'foo'
        }
    },

    changeHandler: function(value) {
        this.setState({
            value: value
        });
    },

    render: function() {
        return (
            <div>
                <Child value={this.state.value} onChange={this.changeHandler} />
                <span>{this.state.value}</span>
            </div>
        );
    }
});

var Child = React.createClass({
    propTypes: {
        value:      React.PropTypes.string,
        onChange:   React.PropTypes.func
    },
    getDefaultProps: function() {
        return {
            value: ''
        };
    },
    changeHandler: function(e) {
        if (typeof this.props.onChange === 'function') {
            this.props.onChange(e.target.value);
        }
    },
    render: function() {
        return (
            <input type="text" value={this.props.value} onChange={this.changeHandler} />
        );
    }
});

In the above example, Parent calls Child with a property of value and onChange. The Child in return binds an onChange handler to a standard <input /> element and passes the value up to the Parent's callback if it's defined.

As a result the Parent's changeHandler method is called with the first argument being the string value from the <input /> field in the Child. The result is that the Parent's state can be updated with that value, causing the parent's <span /> element to update with the new value as you type it in the Child's input field.

Upvotes: 165

Related Questions