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?
This is because history is undefined when you call this.props.history.push();. You must pass that prop down to your ListEmployeeComponent component. You could also transform that component into a functional component like your <App /> component so that you can utilize a hook called useNavigate from react-router-dom. Below is a snippet that shows how we could utilize useNavigate so that we don't have to pass props down the component tree. Again, you will need to convert your ListEmployeeComponent component to a functional component for this to work:
'
import { useNavigate } from 'react-router-dom';
export default function LinkButton({ children }: LinkButtonProps) {
const navigate = useNavigate();
function handleNavigate() {
navigate('/dashboard');
}
return (
<LinkButtonComponent onClick={handleNavigate}>
{children}
</LinkButtonComponent>
);
}
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.
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={}/>}/>
...
)
}