Search code examples
reactjsasynchronouscomponentssetstate

Is there any signal that parent component's state set and then child component's state set too?


when parent component set state(itemSelected: item) i want child component set state(isShowForm: true) too, so is there any signal or condition let me do that thing?

<pre>
//this is child Component
class HeaderComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isShowForm: false,
    };
  }

  handleEdit = () =>{
    if(any signal?){
      this.setState({isShowForm:true})
    }
  }
export default HeaderComponent;

//this is parent Component 
class Task extends Component {
  constructor(props){
    super(props);
    this.state = {
      itemSelected: null,
    }
  }
handleEdit = (item) => {
    this.setState({itemSelected: item})
  }
render() {

    let {itemSelected} = this.state;
return(
 HeaderComponent itemSelected={itemSelected}/>
)

</pre>

Solution

  • You can pass the required state from parent component to child and use componentDidUpdate lifecycle in child to listen to the prop and react accordingly.

    class HeaderComponent extends Component {
      constructor(props) {
        super(props);
        this.state = {
          isShowForm: false,
        };
      }
    
      componentDidUpdate(prevProps) =>{
        // Any identifying property to see if the itemSelected object has indeed changed. I'm just assuming that it has a unique ID
        if(prevProps.itemSelected && prevProps.itemSelected.id !== this.props.itemSelected.id) {
          this.setState({ isShowForm: true })
        }
      }
    export default HeaderComponent;
    
    //this is parent Component 
    class Task extends Component {
      constructor(props){
        super(props);
        this.state = {
          itemSelected: null,
        }
      }
    handleEdit = (item) => {
        this.setState({itemSelected: item})
      }
    render() {
    
        let {itemSelected} = this.state;
    return(
     <HeaderComponent itemSelected={itemSelected}/>
    )