Friday, May 11, 2018

Callback Function With Parameters ReactJS

If you need to call the parent component method when click the button in the child component, you can use the callback function as passing the function.

Bind the event in the constructor.

class Parent extends Component {
constructor(props, context) {
super(props, context);
this.print = this.print.bind(this);
}

Method implementation in the parent component.

print(textData){
const text = textData;
}

Parent class render method pass the function as a prop

render() {
return (
<div>
{<DownloadPDF onPrint={this.print} />}
</div>
);
}

Child component bind the event in constructor


class DownloadPDF extends Component {
constructor(props, context) {
this.onDownload = this.onDownload.bind(this);
}


Call to the Parent component method as a prop

onDownload(){
this.props.onPrint("Eranda");
}

render() {
return (
<div>
<button
className="btn clr-btn"
onClick={this.onDownload}>Download
</button>
</div>
);
}