Home > Blockchain >  How can i unmount a functional component from DOM on click on a Button
How can i unmount a functional component from DOM on click on a Button

Time:07-04

I would like to "Unmount a simple Functional Component" from the DOM. I searched a lot and saw most of the tutorials are based on Class Components and I did'nt see any simple example on it. My requirement is Unmounting a Functional component from the DOM on click on a button. Following is the component with the button which i likes to unmount when click on it. Hopes someone can help me to do it. Thanks in Advance !

import React from 'react'

function App() {
 return (
    <div className='app-component'>
      <h2 className="h2">App Component</h2>
      <button>Unmount This Component</button>
    </div>
  )
}

export default App

CodePudding user response:

If you want to unmount a component then you can use conditional rendering where you can declare state in parent component and based on the state you can mount or unmount component as:

This is the parent component from where you want to mount or unmount

CODESANDBOX DEMO

If you want to toggle component once then you can do the following because there is only one way to change state i.e from Test component. If you unmount this component there is no way to mount it again. So you can also declare button in App component from where you can mount or unmount on click of a button. CODESANDBOX

Parent component

export default function App() {
  const [isShowing, setIsShowing] = useState(true);  // STATE
  return (
    <div className="App">
      {isShowing && <Test setIsShowing={setIsShowing} />}
    </div>
  );
}

Child component

function Test({ setIsShowing }) {
  function unmountComponent() {
    setIsShowing(false);
  }
  return (
    <div className="app-component">
      <h2 className="h2">App Component</h2>
      <button onClick={unmountComponent}>Unmount This Component</button>
    </div>
  );
}

CodePudding user response:

You can use state flag for removing element like this:

import React from 'react'

function App() {
const [flag,setFlage]=useState(true);
 return (
    <div className='app-component'>
      {flag?<h2 className="h2">App Component</h2>:null}
      <button onClick={()=>setFlag(!flage)} >Unmount This Component</button>
    </div>
  )
}

export default App
  • Related