Search code examples
reactjsclassurlparametersreact-class-based-component

How to get params id in react class component


I want a params id from the url in this class component

App.js

<Switch>
    <Route exact path="/products/:id">
       <AuthChecker>
          <Products />
       </AuthChecker>
    </Route>
</Switch>
    

Products.js

import React, { Component } from 'react'
    
    class Products extends Component {

     //How to get params id in this class component

      render() {
        return (
          <div>
            <h5></h5>
          </div>
        )
      }
    }

   export default Products
            

I did check out some questions but I don't get for class component

Thanks in advance


Solution

  • Use match.params for that in combination with Route's render prop:

    <Switch>
        <Route exact path="/products/:id" render={({ match }) => (
           <AuthChecker>
              <Products id={match.params.id} />
           </AuthChecker>
        )} />
    </Switch>