useState Modal React code example

Example: open modal useState

<script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script>
<div id="App"></div>
<script type="text/babel">
  const {useState} = React;

function App() {
  const [openModal, setOpenModal] = useState(false);

  const toggleModal = () => {
    setOpenModal(!openModal);
  }

  return (
    <div className="container">
      {!openModal ?
      <button type="button" onClick={toggleModal}>Open Modal</button>
      : <Modal handler={toggleModal} />
      }
    </div>
  )
}

function Modal({handler}) {

  return (
    <div className="modal" >
      <p>I'm a modal</p>
      <button type="button" onClick={handler}>Close Modal</button>
    </div>
  )
}

ReactDOM.render(<App />, document.getElementById('App'));
 </script>

Tags:

Misc Example