0

I have a question, how can i unmount component by itself. so basically, when i click the component it should unmount itself without calling the parent component, hide/show properties. here is a sample of my code.

onClose = () => {
    let mountNode = ReactDOM.findDOMNode(this);
    ReactDOM.unmountComponentAtNode(mountNode);
}
Jap Mul
  • 17,398
  • 5
  • 55
  • 66
ping pong
  • 163
  • 3
  • 12
  • What's wrong with this code? Does it not work? – AKX Jun 05 '19 at 14:01
  • 2
    Possible duplicate of [How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message](https://stackoverflow.com/questions/36985738/how-to-unmount-unrender-or-remove-a-component-from-itself-in-a-react-redux-typ) – Jap Mul Jun 05 '19 at 14:02
  • Here is the answer, thoughts on this sol'n var par = ReactDOM.findDOMNode(this).parentNode; par.removeChild(ReactDOM.findDOMNode(this)); ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this) as HTMLElement); – ping pong Jun 05 '19 at 14:14

1 Answers1

2

You could store a reference to the node the component is mounted on the component instance returned by ReactDOM.render() using a ref callback.

class Thing extends React.Component {
  onClose = () => {
    ReactDOM.unmountComponentAtNode(this.mountNode);
  }
}
const node = document.getElementById("root");
const inst = ReactDOM.render(<Thing ref={(inst) => inst.mountNode = node} />, node);

(Edited to use ref, cheers @hawk.)

AKX
  • 152,115
  • 15
  • 115
  • 172
  • Why not callback prop? – hawk Jun 05 '19 at 14:07
  • i dont want a callback , it's up to the developer if they want a callback or not. just think of a lightbox on jquery.you can subscribe an optional callback for closing or ok button – ping pong Jun 05 '19 at 14:11
  • but yeah, here is the solution, i need some eyes code review on this. var par = ReactDOM.findDOMNode(this).parentNode; par.removeChild(ReactDOM.findDOMNode(this)); ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this) as HTMLElement); – ping pong Jun 05 '19 at 14:13
  • I strongly against modifying the DOM yourself in this case – keul Jun 05 '19 at 14:27
  • @keul, what is your suggestion? – ping pong Jun 05 '19 at 15:09