2

I am trying to figure out how to convert this code

const Child = ({ match }) => (
  <div>
    <h3>ID: {match.params.id}</h3>
  </div>
)

Into a class based component like this

class Home extends React.Component {

  render() {
      ....
  }
}

Normal const components I know how to convert, but I am not able to understand how to include match parameter in class based component.

KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
Abhinav
  • 3,322
  • 9
  • 47
  • 63
  • 1
    `{ match }` would generally either map to `this.props.match` or `this.state.match` in a class based component when you are converting it. Depending on whether match is likely to change during the lifecycle of the component. If match is likely to change, make it a state variable, otherwise, make it a prop variable. Also, how you create the child component in the parent component will need to be reviewed in order to ensure you pass props or state correctly. – Finbarr O'B Jul 25 '17 at 08:06

2 Answers2

7

In your functional component definition

const Child = ({ match }) => (
  <div>
    <h3>ID: {match.params.id}</h3>
  </div>
)

The argument is the props passed down to the Child component, however when you use {match} you are detructuring only the prop match from all the props passed down.

See this answer: What is the children prop in React component and what PropTypes do

So when converting your functional component to the class component you can destructure the prop match in the render function like

class Child extends React.Component {

  render() {
      var {match} = this.props;
      return (
         <div>
             <h3>ID: {match.params.id}</h3>
           </div>
      )
  }
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
1

function:

const Child = ({ match }) => (
  <div>
    <h3>ID: {match.params.id}</h3>
  </div>
)

Class:

import React, { Component } from 'react';

class Child extends Component {
  render(){
    const {match} = this.props;
    return (
      <div>
         <h3>ID: {match.params.id}</h3>
       </div>
    );
  }
}
export default Child;
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133