Cannot read properties of undefined (reading 'params') - in this.props.match.params.id in EditExercise.js ,ReactJS

Viewed 41

I am following a tutorial, it uses an old version of react therefore all components are class components, the edit exercise component has a componentDidMount with a this.props.match.params.id that checks the id in the url,

The Edit Exercise.js the file with the componentDidMount

class EditExercise extends Component{
  
    constructor(props){
        super(props )
        
       
        this.state={
            username:"",
            description:"",
            duration:0,
            date:new Date(),
            users:[]
        }
  
    }
    
  componentDidMount(){
      
      axios.get('http://localhost:5000/exercises/'+ this.props.match.params.id)
      .then(response=>{
        this.setState({
          username:response.data.username,
          description:response.data.description,
          duration:response.data.duration,
          date: new Date(response.data.date)
        })
      } ).catch (function(error){
        console.log(error)
      })
...

And the Routes of this app is as below

function App() {
  return (
    <Router>
      <Navbar/>
       <Routes>
       <Route index element ={<ExercisesList/>}/>
        <Route path="edit/:id"  element ={<EditExercise/>}/>
       </Routes> 
    </Router>
  );
}

The error I get says,

Uncaught TypeError: Cannot read properties of undefined (reading 'params')

I have tried using withRoutes and it requires me to downgrade react-router-dom which I wont be able to do because of how it complicates the routes afterwards, so I would like to keep the react-router-dom version as is

1 Answers

Since react-router version 2.7 a Higher Order Component (HOC) has been added - withRouter

All components where access to parameters is required, wrap in withRouter (more) - then you will get what you need in props


@withRouter
class App extends ...

ES6:

class App extends ...

export default withRouter(App)
Related