How to set variable from parent inside child's componentDidMount react?

Viewed 378

I am trying fetch the information from Api request in child component. The problem is that I have faced accessing parent's props. More precisely how to get parent's props and set it inside componentDidMount()? Parent component

class Parent extends Component {
  constructor(){
    super()
  }
...
<Child id={id}/>
...

export default Parent;

Child component

class Child extends Component {
  constructor(){
    super()
    this.state = { 
      id:'',
    }
  }

  // I need somehow set parent's "id" inside the url
  componentDidMount() {
    const url = `https://api.../${id}?api_key=${apiKey}`;

        axios.get( url )
        ...
    };

  render(){

    const { id } = this.props;
    console.log('Child id ' + id) // here I see all ids

    return(
      <div className="item" key={id}>
        <p>{id}</p> // here as well
      </div> 
    )
  }
}

Child.propTypes = {
  item: PropTypes.object
}
export default Child;

Maybe I am looking for in the wrong place and I need just change logic. I will be grateful for any advice

2 Answers

To access props from anywhere in your Child component you need to pass props to your constructor, then you just access it using this.props.

This should work:

class Child extends Component {
  constructor(props){
    super(props)
    this.state = {},
  }

  componentDidMount() {
    const id = this.props.id
    const url = "https://api.../$" + id + "?api_key=${apiKey}";

        axios.get( url )
        ...
    };
}

If you have a constructor in a component the props should always be passed to the constructor and also to React component using super()

constructor(props){
    super(props)
}

In your case if you have to use your parents props you should also pass the parents props to child also and with same syntax in constructor you can use props that you passed in anywhere of the child component and you can set that props in componentDidMount as well

Related