Home > Back-end >  this.props is empty in React v6
this.props is empty in React v6

Time:08-29

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",

CodePudding user response:

If you are going to use react-router6 then you need to use react hooks to pass router data and there are 2 options:

  1. rewrite your class component to a functional one;
  2. create a functional wrapper around your class component - https://github.com/remix-run/react-router/issues/8146#issuecomment-947860640

also an example from the issue thread:

import React,{ Component} from "react";
import { useNavigate } from "react-router-dom";

export const  withNavigation = (Component : Component) => {
  return props => <Component {...props} navigate={useNavigate()} />;
} 

//classComponent  
class LoginPage extends React.Component{

submitHandler =(e) =>{
    //successful login 
    this.props.navigate('/dashboard');
  }
}
export default withNavigation(LoginPage);

CodePudding user response:

use render to prop pattern as shown below: This will pass all routing related properties to your component( in react router 4)

 <Route
    path="/"
    exact
    render={(props: any) => <ListEmployeeComponent {...props} />}  
  ></Route>

In react router 6:

import { createBrowserHistory } from "history";

use const history = createBrowserHistory(); in your component to access
import { useNavigate } from "react-router-dom";

use like this < ListEmployeeComponent history={useNavigate()} />

To use location: import { useLocation } from "react-router-dom";

  • Related