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>
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>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With