George
George

Reputation: 69

React - Set state in child?

I'm new to Reacts. I read a lot post and I can not find a solution to my problem.

I have several components. One is Gallery on which ajax request is called to get values.Another component is InnerContent. Its a child component of Gallery.

My question is it correct to set state as props in child component, in my case (InnerContent)?

This is my input data:

[
      {
        "collection": 1,
        "article": 1,
        "name": "Gallery 2",
        "images": [{
            "id": 2,
            "name": "aaa",
            "src": "http://via.placeholder.com/200x200"
          },
          {
            "id": 3,
            "name": "bbb",
            "src": "http://via.placeholder.com/200x200"
          }
        ]
      }
    ]

Here is my code:

    class InnerContent extends Component {
  constructor(props){
    super(props);

    this.state = {
      images: this.props.data.images,
    };
  }

 removeImage() {
   /*change state in this Component*/
 }

  render() {
    return (
      <div>
        <div>Gallery name: {this.props.data.name}</div>
        <GalleryImageContent>
          <SortableItem removeImage={this.removeImage} {...this.state} />
        </GalleryImageContent>
      </div>
    );
  }
}

function Content(props) {
  let rows = [];

  props.data.forEach((data) => {
    rows.push(<InnerContent data={data}/>)
  });

  return (
    <div>
      {rows}
    </div>
  );
}

class Foo extends Component {
  constructor(props){
    super(props);

    this.state = {
        data: Service.data
    };
  }

  render() {
    return(
      <div>
        <button onClick={/*change state*/}>Add Gallery</button>
        <Content data={this.state.data}/>
      </div>
    );
  }
}

Upvotes: 1

Views: 2942

Answers (1)

Abhinav Jain
Abhinav Jain

Reputation: 339

It is okay to set state as props in child component.

You have to just take care of one more condition in your case. You're setting the state in a constructor, but when the component is rendered the second time and the props change, the state remains the same as the constructor is called only once.

Basically, you have to keep the component's state up to date with the props. You can use componentWillReceiveProps(nextProps) function to solve this.

componentWillReceiveProps(nextProps) {
  this.setState({
    images: nextProps.data.images
  });
}

Let me know if it solves your problem.

Upvotes: 2

Related Questions