use ref to remove html node?

Viewed 515

how to avoid using state but use ref to remove html element?

export default function App() {
  const divRef = useRef();
  return (
    <div className="App">
      <div ref={divRef}>
        <div
          onClick={() => {
            console.log(divRef.current);
          }}
        >
          click to remove this node
        </div>
      </div>
    </div>
  );
}

removeChildren don't exist on current?

3 Answers

divRef.current.removeChild, not removeChildren

<div
  onClick={() => {
    console.log(divRef.current);
    divRef.current.removeChild(divRef.current.children[0])
  }}
>

I'm unsure if you want to remove the child or the node which you have passed ref. If you want to remove child, you can use bellow snippet:

export default function App() {
  return (
    <div className="App">
      <div>
        <div
          onClick={(e) => {
            console.log(e.target.current);
          }}
        >
          click to remove this node
        </div>
      </div>
    </div>
  );
}

However if you want to remove the element you have passed ref you can use the same method check with bellow snipped.

export default function App() {
  const divRef = useRef();
  return (
    <div className="App">
      <div ref={divRef}>
        <div
          onClick={() => {
            console.log(divRef.current.remove());
          }}
        >
          click to remove this node
        </div>
      </div>
    </div>
  );
}

Check out this codesanbox

Yes, This HTML Element can be remove without using UseState Hook.

import { useRef } from "react";

export default function App() {
  // Init UseRef Hook
  const divElement = useRef();

  return (
    <div className="App">
      <div ref={divElement}>
        <div
          onClick={() => {
            divElement.current.remove();
          }}
        >
          click to remove this node
        </div>
      </div>
    </div>
  );
}

Using the OnClick, we are removing the divElement from the useRef.

Here is the Sandbox link

Related