Home > OS >  how fix props.match undefined
how fix props.match undefined

Time:04-18

this is my Editstudent.js

async componentDidMount() {
    const stud_id = this.props.match; 
    console.log(stud_id);
}

this is my App.js

  <Routes>
    <Route exact path="/" element={<Student/>} />
    <Route path="/add-student" element={<Addstudent/>} />
    <Route path="/edit-student/:id" element={<Editstudent/>} />
  </Routes>

but i got error, it said undefined what should I do?

CodePudding user response:

In your case, you should wrap Editstudent.js in withRouter

import { withRouter } from "react-router";

class EditStudent extends React.Component {
   async componentDidMount() {
     const stud_id = this.props.match; 
     console.log(stud_id);
   }
}

export default withRouter(EditStudent);

You can check this document for a better understanding


If you use react-router-dom v6 which does not support class-based components, you can have HOC (higher-order component) with react router hooks (useMatch, useParams, etc.) like below

import { useMatch } from "react-router-dom";

//HOC like this
function withMatch(Component) {
  return props => <Component {...props} match={useMatch()} />;
}

class EditStudent extends React.Component {
   async componentDidMount() {
     const stud_id = this.props.match; 
     console.log(stud_id);
   }
}

//use `withMatch` as a wrapper
export default withMatch(EditStudent);

Or you can convert your component to function-based components and then use hooks directly

import { useMatch } from "react-router-dom";

const EditStudent = () =>  {
   const match = useMatch();
   useEffect(() => {
     const stud_id = match; 
     console.log(stud_id);
   }, []) //similar to `componentDidMount`

   return <div></div> //similar to `render()`
}

export default EditStudent;
  • Related