Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS add callback function to children component

I want to attach a callback to a already created react component, is this possible?

This is my wrapper class, I want to call the callbackToCall from the existing children:

import React from 'react';
class MyComponent extends React.Component {

    callbackToCall() {
        console.log("callback called.");
    }    

    render() {
        const {children} = this.props;
        // Here I want to attach the callback to call
        // E.g. children.props.callback = callbackToCall;
        return (
        <div>
            MyStuff
            {children};
        </div>
        ); 
    }
}

Child class, which does not have any callback to the container class:

import React from 'react';
class Child extends React.Component {

    render() {
        return <button onClick={this.props.callback}>Click me</button>
    }
}

This is the call of my component, here I don't know how to reference the callback:

<MyComponent>
    <Child /* Here I cannot set the callback callback={...callbackToCall}*/ />
</MyComponent>
like image 321
Kevin Wallis Avatar asked Sep 14 '25 20:09

Kevin Wallis


1 Answers

Given that MyComponent is a wrapper that accepts the only child and supposed to provide callback prop to it, it should be:

class MyComponent extends React.Component {
    ...
    render() {
        const child = React.cloneElement(
          React.Children.only(this.props.children),
          { callback: this.callbackToCall }
        );

        return (
          <div>
            MyStuff
            {child};
          </div>
        ); 
    }
}

Alternatively, MyComponent can be provided with a component instead of an element through a prop, like:

class MyComponent extends React.Component {
    ...
    render() {
        return (
          <div>
            MyStuff
            <this.props.component callback={this.callbackToCall}/>
            {this.props.children};
          </div>
        ); 
    }
}

This way MyComponent can additionally accept children for other purposes like <MyComponent component={Child}>...</MyComponent>.

like image 63
Estus Flask Avatar answered Sep 17 '25 10:09

Estus Flask