0

I want to navigate to a new page when clicking on a button. I used history but it not working. Using React-router-dom v6.

App.js

import React from 'react';
import './App.css';
import {BrowserRouter as Router, Route, Routes} from 'react-router-dom'
import ListEmployeeComponent from './components/ListEmployeeComponent';
import HeaderComponent from './components/HeaderComponent';
import FooterComponent from './components/FooterComponent';
import CreateEmployeeComponent from './components/CreateEmployeeComponent';

function App() {
  return (
    <div>
        <Router>
              <HeaderComponent />
                <div className="container">
                    <Routes> 
                          <Route path = "/" index element = {<ListEmployeeComponent/>}></Route>
                          <Route path = "/employees" element = {<ListEmployeeComponent/>}></Route>
                          <Route path = "/add-employee" element = {<CreateEmployeeComponent/>}></Route>
                    </Routes>
                </div>
              <FooterComponent />
        </Router>
        
    </div>
    
  );
}

export default App;

ListEmployeeComponent.js

import React, { Component } from 'react'
import EmployeeService from '../services/EmployeeService';

// import { createHashHistory } from 'history'
// export const history = createHashHistory()
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');
    }
    
  render() {
    return (
      <div>
           <h2 className="text-center">Employees List</h2>
           <div className = "row">
                    <button className="btn btn-primary" onClick={this.addEmployee}> Add Employee</button>
            </div>
                 <br></br>
            <table className='table table-striped table-bordered'>
                <thead>
                    <tr>
                        <th>Employee First Name</th>
                        <th>Employee Last Name</th>
                        <th>Employee Email Id</th>
                        <th>Actions</th>
                    </tr>
                </thead>

                <tbody>
                    {
                        this.state.employees.map(
                            employee => 
                            <tr key ={employee.id}>
                                <td>{employee.firstName}</td>
                                <td>{employee.lastName}</td>
                                <td>{employee.emailId}</td>
                            </tr>
                        )
                    }
                </tbody>
            </table>
      </div>
    )
  }
}
export default ListEmployeeComponent 

CreateEmployeeComponent.js

import React, { Component } from 'react'
// import EmployeeService from '../services/EmployeeService';
// import { createHashHistory } from 'history'
// export const history = createHashHistory()

class CreateEmployeeComponent extends Component {
    constructor(props) {
        super(props)

        this.state = {
            // id: this.props.match.params.id,
            firstName: '',
            lastName: '',
            emailId: ''
        }
        this.changeFirstNameHandler = this.changeFirstNameHandler.bind(this);
        this.changeLastNameHandler = this.changeLastNameHandler.bind(this);
        this.saveOrUpdateEmployee = this.saveOrUpdateEmployee.bind(this);
        
    }

    saveOrUpdateEmployee = (e) => {
        e.preventDefault();
        let employee = {firstName: this.state.firstName, lastName: this.state.lastName, emailId: this.state.emailId};
        console.log('employee => ' + JSON.stringify(employee));
    }


    changeFirstNameHandler= (event) => {
        this.setState({firstName: event.target.value});
    }

    changeLastNameHandler= (event) => {
        this.setState({lastName: event.target.value});
    }

    changeEmailHandler= (event) => {
        this.setState({emailId: event.target.value});
    }

    cancel(){
        this.props.history.push('/employees');
    }
    render() {
        return (
            <div>
               <div className='container'>
                   <div className='row'>
                       <div className='card col-md-6 offset-md-3 offset-md-3'>
                        <h3 className='text-center'>Add Employee</h3>
                        <div className='card-body'>
                            <form>
                                <div className='form-group'>
                                <label> First Name: </label>
                                            <input placeholder="First Name" name="firstName" className="form-control" 
                                                value={this.state.firstName} onChange={this.changeFirstNameHandler}/>
                                </div>
                                <div className = "form-group">
                                            <label> Last Name: </label>
                                            <input placeholder="Last Name" name="lastName" className="form-control" 
                                                value={this.state.lastName} onChange={this.changeLastNameHandler}/>
                                        </div>
                                        <div className = "form-group">
                                            <label> Email Id: </label>
                                            <input placeholder="Email Address" name="emailId" className="form-control" 
                                                value={this.state.emailId} onChange={this.changeEmailHandler}/>
                                        </div>
                                        <button className="btn btn-success" onClick={this.saveOrUpdateEmployee}>Save</button>
                                        <button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button>
                            </form>
                        </div>
                       </div>

                   </div>
                </div>
            </div>
        )
    }
}

export default CreateEmployeeComponent

How to resolve this Type Error: Cannot read properties of undefined (reading 'push') in React Js. Please rectify. WithRouter is all not working. Hash history also not working. I am using react-router-dom v6. Please rectify how to clear this in class component.Navigate router is not working

1
  • General rule of thumb with these types of errors is either it's not set up correctly or you're not accounting for default values; if undefined or null is the default value, you have to wrap function calls in conditionals checking to see if the variable/object is set before use. Commented Apr 22, 2022 at 16:38

1 Answer 1

2

In react-router v6, you have to use "navigate" function. Check this :https://reactrouter.com/docs/en/v6/getting-started/overview#navigation

Sign up to request clarification or add additional context in comments.

2 Comments

Where to change? , can you edit the code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.