'How to hide and show element React

I have tried and require to be able to hide and show the test field with the click of the button in the code. I have tried other ways but i need to be able to do it with the code starting with const About...

const About = () => {
  return (
    <div>
      <center>
        <hr/>
        <button>Show and hide element</button>
        {
          <div style={{ marginTop: "100px" }}>
            <form
              style={{
              margin: "auto",
              padding: "15px",
              maxWidth: "400px",
              alignContent: "center",
              }}
            >
              <label htmlFor="Test">Test</label>                 
              <input
                type="text"
                id="test"                                           
                name="test"
              />
            </form>
          </div>
        }
      </center>
    </div>
  );
};

ReactDOM.render(
  <div>
    DEMO
    <About />
  </div>,
  document.getElementById("rd")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.0/umd/react-dom.production.min.js"></script>
<div id="rd" />


Solution 1:[1]

You can just toggle it using state:

Check useState line and conditional rendering with show &&.

(working example here )


const {useState, useEffect} = React;


const About = () => {

    const [show, setShow] = useState(true)

  return (
    <div>
      <center>
        <hr/>
        <button onClick={()=>setShow(!show)}>Show and hide element</button>
        {
        show &&
          <div>
            <form
              style={{
              margin: "auto",
              padding: "15px",
              maxWidth: "400px",
              alignContent: "center",
              }}
            >
              <label htmlFor="Test">Test</label>                 
              <input
                type="text"
                id="test"                                           
                name="test"
              />
            </form>
          </div>
        }
      </center>
    </div>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<About/>)

Solution 2:[2]

You can use react hook useState and set states as show/hide and update the state when you click the button and use conditional rendering to show or hide the element using state.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Alfonso Tienda
Solution 2 Selvaganapathy