Reputation: 311
I have 2 components. One extendind another like this
export default class Parent extends React.Component {
myCustomFunction = () => {
..
this.setState({
myVar: 'pippo'
});
}
}
export default class Child extends Parent {
myCustomFunction = () => {
//I want to call here my parent myCustomFunction
..
this.setState({
myVar: 'pluto',
otherVar: 'paperino'
});
}
render (){
return
<button onClick={this.myCustomFunction } />
}
}
When someone click on button in Child I want to run the Parent function and then do some other stuff on the state.
How can I achieve this without coping the Parent in the Child?
Upvotes: 2
Views: 593
Reputation: 1022
There's lots of approaches but I think you're looking for how to inherit the Parent's function like you would traditionally in any class inheritance model.
class Parent extends React.Component {
constructor() {
super();
}
parentFunc() {
console.log(`Parent`);
}
}
class Child extends Parent {
constructor() {
super();
}
childFunc() {
console.log(`Child`);
super.parentFunc();
}
render() {
return <button onClick={this.childFunc}>Click me</button>;
}
}
CodeSandbox here https://codesandbox.io/s/k3n1664323
MDN docs on super() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super
p.s. You cannot call super
in the context of an arrow function, you will need to use a regular function expression or take a different approach, potentially like the other answer suggested. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions
Upvotes: 3