How to include the Match object into a ReactJs component class?

Viewed 20830

I am trying to use my url as a parameter by passing the Match object into my react component class. However it is not working! What am I doing wrong here?

When I create my component as a JavaScript function it all works fine, but when I try to create my component as a JavaScript class it doesn't work.

Perhaps I am doing something wrong? How do I pass the Match object in to my class component and then use that to set my component's state?

My code:

import React, { Component } from 'react';

import axios from 'axios';

import PropTypes from 'prop-types';

class InstructorProfile extends Component {  

  constructor(props, {match}) {

    super(props, {match});

    this.state = {
        instructors: [],
        instructorID : match.params.instructorID
    };

  }

   componentDidMount(){


      axios.get(`/instructors`)
      .then(response => {
        this.setState({
          instructors: response.data
        });
      })
      .catch(error => {
        console.log('Error fetching and parsing data', error);
      });
    }

  render(){
    return (
      <div className="instructor-grid">

        <div className="instructor-wrapper">

       hi

        </div>

      </div>
    );
  }
}

export default InstructorProfile;
5 Answers

for me this was not wrapping the component:

export default (withRouter(InstructorProfile))

you need to import withRouter:

import { withRouter } from 'react-router';

and then you can access match params via props:

  someFunc = () => {
      const { match, someOtherFunc } = this.props;
      const { params } = match;
      someOtherFunc(params.paramName1, params.paramName2);
  };

In a functional component match gets passed in as part of props like so:

export default function MyFunc(props) {
//some code for your component here...
}

In a class component it's already passed in; you just need to refer to it like this:

`export default class YourClass extends Component {
     render() {
        const {match} = this.props;
        console.log(match);
        ///other component code 
    }
}`
Related