Below is the code of ListEmployeeComponent
import React, { Component } from 'react';
import EmployeeService from '../service/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(){
this.props.history.push("/add-employee");
}
....
....
export default ListEmployeeComponent
And this one is of App.js code
import React from 'react';
import logo from './logo.svg';
import './App.css';
import {BrowserRouter as Router} from 'react-router-dom';
import {Routes, Route} from 'react-router';
import ListEmployeeComponent from './Component/ListEmployeeComponent';
import HeaderComponent from './Component/HeaderComponent';
import FooterComponent from './Component/FooterComponent';
import CreateEmployeeComponent from './Component/CreateEmployeeComponent';
function App() {
return (
<div>
<Router>
<HeaderComponent/>
<div className="container">
<Routes>
<Route exact path="/" element={<ListEmployeeComponent/>}/>
<Route path="/employees" element={<ListEmployeeComponent/>}/>
<Route path="/add-employee" element={<CreateEmployeeComponent/>}/>
</Routes>
</div>
<FooterComponent/>
</Router>
</div>
);
}
export default App;
I want to navigate my page to the add-employee page but when I click on that button I'm getting an error as "Cannot read properties of undefined (reading 'push')"
Can anyone please help me with this?
CodePudding user response:
import { useHistory } from "react-router-dom";
let history = useHistory();
In react there is useHistory hook which can be used like this instead of this.props.push. This will solve your problem.
CodePudding user response:
Note that you get the history value from the props, but when defining the component in the program, you did not add any properties called history to the component.
function App() {
...
return (
...
<Route exact path="/" element={<ListEmployeeComponent histoy={}/>}/>
...
)
}
