2

I am trying to get url params using react js. My Route is

<Route exact path="/store/product-details/:id" component = {StoreProductDetails} />

ProductDetail.js

componentDidMount(){
      let id = this.props.match.params.id
      fetch(MyGlobleSetting.url + 'product/'+ id)
      .then(response => response.json())
      .then(json => this.setState({ singleProduct: json.data }));
    }

enter image description here

1

1 Answer 1

3

You can use the useParams hook or wrap a class based component with the withRouter HOC from react-router. You can see an example in their documentation.

Using functional components

import React, {useEffect} from 'react';
import {useParams} from 'react-router-dom';

function Child() {
  // We can use the `useParams` hook here to access
  // the dynamic pieces of the URL.
  let { id } = useParams();

  useEffect(() => {
     fetch(MyGlobleSetting.url + 'product/'+ id)
      .then(response => response.json())
      .then(json => this.setState({ singleProduct: json.data }));
  }, [])
}

Using a class component

import React, {Component} from 'react';
import { withRouter } from 'react-router-dom';

class myComponent extends Component {

  componentDidMount(){
     const {match} = this.props

     fetch(MyGlobleSetting.url + 'product/'+ match.params.id)
      .then(response => response.json())
      .then(json => this.setState({ singleProduct: json.data }));
  }
}

export default withRouter(Child);
Sign up to request clarification or add additional context in comments.

4 Comments

how is it possible class life-cycle componentDidMount work with functional component ?
You're absolutely correct. I'm so used to functional programming it want straight over my head. I'll fix it now
i think still wrong, functional component doesn't have componentDidMount. Its a lifecycle method of react class component reactjs.org/docs/react-component.html#componentdidmount
And again you're correct hahahahah That's what I get for doing 3 things at the same time

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.