Reputation: 55
I have a parent class component that has a functional child table component. When a user selects a row in the table component, I am attempting to capture the row data (the data is an object), return it to the parent component, and then save it to the state. I am currently running into the following error: Uncaught TypeError: Cannot read property 'setState' of undefined
I've referenced this Stack question, but this does not save the value from the child component to the state in the parent component: How to pass value from a child functional component to parent class component?
Question: How can I save the value to the state?
Parent class component
class ParentComponent extends Component {
constructor(props) {
super(props);
this.state = {
selectedRows: []
};
}
setSelectedDataTableRow(selectedRow) {
console.log('setSelectedDataTableRow triggered!', selectedRow);
this.setState({selectedRows: selectedRow}) //this is causing the error
}
render() {
return (
<>
<ChildComponent
otherProps={otherProps}
setSelectedDataTableRow={this.setSelectedDataTableRow}
/>
</>
);
}
}
Child functional component
const ChildComponent = ({ otherProps, setSelectedDataTableRow }) => {
const ROWS_PER_PAGE = 5;
const captureRowData = (data) => {
setSelectedDataTableRow(data)
}
return (
<div>
<DataGrid
//other attributes
onRowSelected={(e) => captureRowData(e.data)}
/>
</div>
);
};
Upvotes: 1
Views: 146
Reputation: 55
The solution provided by Dave in the comments did the trick. Posting it here as the answer:
setSelectedDataTableRow={this.setSelectedDataTableRow}
updated to
setSelectedDataTableRow={this.setSelectedDataTableRow.bind(this)}
Upvotes: 1