I have this component which is basically a button that adds an Employee to a database:
import React, { Component } from "react";
import EmployeeService from "../services/EmployeeService";
class ListEmployeeComponent extends Component {
constructor(props) {
super(props);
this.state = {
employees: [],
};
this.addEmployee=this.addEmployee.bind(this);
}
componentDidMount() {
EmployeeService.getEmployees().then((res) => {
this.setState({ employees: res.data });
});
}
addEmployee(){
console.log(this.props.history);
this.props.history.push("/create");
}
render() {
return (
<div>
<h2 className="text-center">Employees List</h2>
<button className="btn btn-primary" onClick={this.addEmployee} >Add Employee</button>
</div>
);
}
}
export default ListEmployeeComponent;
However, this.props is {} and so this.props.history is undefined..
Cannot read properties of undefined (reading 'push')
at ListEmployeeComponent.addEmployee
and this is the instantiation of the component:
<Routes>
<Route path="/" exact element={<ListEmployeeComponent />}></Route>
</Routes>
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.3.0",
"react-scripts": "5.0.1",