A
A
Artem2019-03-11 15:59:55
React
Artem, 2019-03-11 15:59:55

How to safely unmount a component in React?

By clicking on the button in one component, I delete the component in the parent with the following code:

// componentA.jsx
class ComponentA extends React.PureComponent {
  removeB() {
    this.setState({ mounted: false })
  }

  renderB() {
    if (!this.state.mounted) {
      return null
    }
    return <ComponentB />
  }

  render() {
    return <div>
      {this.renderB()}
      <ComponentC onClick={this.removeB} />
    </div>
  }
}

// componentB.jsx
class ComponentB extends React.PureComponent {
  render() {
    return // Какой-то контент
  }
}

// componentC.jsx
class ComponentC extends React.PureComponent {
  render() {
    return <Button onClick={this.props.onClick} />
  }
}

I get the error:
Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2019-04-23
@Cruper

class ComponentA extends React.PureComponent {
  state = { isMounted: true };

  removeB = () => {
    this.setState({ isMounted: false });
  };

  render() {
    const { isMounted } = this.state;

    return (
      <div>
        {isMounted && <ComponentB />}
        <ComponentC onClick={this.removeB} />
      </div>
    );
  }
}

D
Dima, 2019-04-11
@dimakrsna

It's better to do it like this:

// componentA.jsx
class ComponentA extends React.PureComponent {
    state = {
        mounted: false
    }

    removeB = () => {
        this.setState({ mounted: !this.state.mounted })
    }

    render() {
        let { mounted } = this.state
        return <div>
            {
                (mounted) ? <ComponentB /> : <ComponentC onClick={this.removeB} />
            }
        </div>
    }
}


// componentB.jsx
class ComponentB extends React.PureComponent {
    render() {
        return <div>ComponentB</div>
    }
}

// componentC.jsx
class ComponentC extends React.PureComponent {
    render() {
        return <button onClick={this.props.onClick}>ComponentC click me</button>
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question