How to make an http call in parent component to setState and then send the state to all child components?

Viewed 94

So I am trying to make call axios.get('{link here}') from componentDidMount() of parent:

class Parent extends React.Component {
constructor(){
   super();
   this.state = {
       stuff: []
   }
}

componentDidMount() {
     axios.get({link})
     .then(res => {
         this.setState({stuff: res.data}) 
     }
}

render() {
    return(
    <Child stuff={this.state.stuff} />
    )
}

Then there is Child various child components, one of which is like:

class Child extends React.Component {
    constructor(props) {
         super(props);
    }

    render() {
       return(
           //To access everything in the data of parent here in child component
       )    
}

Even though the parent shows data in console.log(), the child is not receiving anything

2 Answers

Inside the class Child you can access the props that were passed down using this.props. It would look something like this:

class Parent extends React.Component {

  state = {
    name: 'Felix'
  }

  render() {
    return (
      <Child name={this.state.name} />
    )
  }
}


class Child extends React.Component {

  render() {
    return <p>My Name is {this.props.name}</p>
  }
}

ReactDOM.render(<Parent />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

If the child component is not going to hold internal state, then you can refactor it into a functional component:

function Child(props) {
  return <p>My Name is {props.name}</p>
}

More info about function and class components here.

Not sure if it's the whole solution, but replace

constructor(){
   super();
   this.state = {
       stuff=[]
   }
}

by

constructor(){
   super();
   this.state = {
       stuff: []
   }
}

You have a = sign inside an object declaration.

Related