I'm tinkering with a React application where I have a Class component and a Functional Component. My Class component has a function for updating a name in its state. I'm trying to pass this function to a Functional Component as a property, the invocation works fine and I can see the argument making it into the method while debugging the application in a browser, but things blow up when trying to invoke this.setState, because 'this' is 'undefined'. I know about React hooks but don't think they are able to deal with a parent components state. Is there a technique for handling this kind of situation?
Note: the below snippets are pseudo code so just assume there's a button and clicking it works
The Class Component
class MyClassComponent extends React.Component {
constructor(props) {
super(props);
this.setName = this.setName.bind(this);
this.state = {
name: '',
};
}
setName(name) {
this.setState({
name: name
});
}
render() {
return (
<MyFunctionalComponent
setName={this.setName}/>
);
}
}
The Functional Component
export const MyFunctionalComponent = props => {
const { setName } = props;
return (
<button onClick={setName('fred')}>
);
};
The exception
Uncaught TypeError: Cannot read property 'setState' of undefined