Tuesday, April 3, 2018

Call a function in child component from parent component in React


Consider the following parent component

class Parent extends React.Component {

constructor(props) {

super(props);

        this.state = { data: "" };

}

handleClick() {

        this.setState({ data: "I am Clicked" });

        this.refs.child.handleChild();

}

render() {

        return (

<div>

<button onClick={this.handleClick.bind(this)} > Click Me</button>

<ChildComponent ref="child" />

</div>

);

}

}
Consider the child component
class ChildComponent extends React.Component {

constructor(props) {

super(props);

        this.state = { childData: "Child function is called" };

}

handleChild() {

alert(this.state.childData)

}

render() {

        return (

<div>            </div>

);

}

}
As shown above we can make use of "ref" on child component and using this.refs we can call any function in the child component







Call a function in child component from parent component in React

Consider the following parent component class Parent extends React.Component { constructor(props) { super(props);         thi...