0

**I'll post the code first and then explain what's the issue I'm getting later.

class ParentComponent extends Component {
  constructor() {
    super()

    this.state = {
      id: null,
    }
}

  render() {
    const dataTarged = "#col" + id
    const id = "col" + id
    return (
      <React.Fragment>
        <div>
          <button data-toggle="collapse" data-target={dataTarged} onClick={() => this.setState({ id: <<this id may vary>> })}>Click me</button>
        </div>

        <div className="collapse mt-4" id={id}>
          <ChildComponent id={this.state.id} />
        </div>
      </React.Fragment>
    )
  }
}



class ChildComponent extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.id != prevProps.id) {
      //do stuff with the ID
    }
  }
}

Explanation:

  1. On the ParentComponent I have that collapse, and on that collapse I'm passing the ID using the this.state.id (which may vary).
  2. That button on click is also toggling the collapse and showing the ChildComponent with it's props.

Scenario:

  1. The ParentComponent is 'card' and I have more than one with different ids.
  2. Whenever I click on the button the state is updated with the new ID from ParentComponent and passed as props to ChildComponent.

Issue I'm facing:

If I toggle different ParentComponents the componentDidUpdate in ChildComponent stops being called and the ID is not updated. Meaning that the information I need to get with that ID is not correct.

Also, the render() on ChildComponent is not being called, it seems that since it rendered once it will not render again.

Thats the issue, componentDidUpdate shouldnt be called everytime the props passed to ChildComponent changes? I'm changing the props passed everytime i toggle a different ParentComponent.

Thanks in advance, I hope I made myself clear

kivul
  • 1,148
  • 13
  • 28
  • you're not assigning a new id here id: <> do you wanna do it later? – MWO Oct 24 '20 at 00:00
  • Your issue reminds me of the different problems I had when I forgot to assign keys to the components. Have you tried assigning id as a key for parent and child components? (e.g. key={`parent-${id}`} / key={`child-${id}`} ) – Anastasiia Solop Oct 24 '20 at 07:06
  • @AnastasiiaSolop i've tried that, no success, componentDidUpdate doesnt get called after i toggled the component – kivul Oct 24 '20 at 17:02

0 Answers0