Hide/show state of div react

Viewed 49

suppose i have a div element

<div
     style={{
                borderTopLeftRadius: "10px",
                borderTopRightRadius: "10px",
                background: "#edf2f8",
                border: "1px solid #edf2f8",
                borderBottom: "0px",
                width:"300px",
                marginLeft:"20px",
                backgroundPosition: "center",
                
              }}

  >
    hello world
 </div>

I want to use the onclick function to hide/show state of the div . For example when a user clicks in the div I hide it .. How can I achieve that in react ?

1 Answers

Store a display value in component state and toggle it via the onClick handler. Conditionally render the entire div.

Example:

function App() {
  const [display, setDisplay] = React.useState(true);

  return (
    <div className="App">
      {display && (
        <div
          onClick={() => setDisplay(false)}
          style={{
            borderTopLeftRadius: "10px",
            borderTopRightRadius: "10px",
            background: "#edf2f8",
            border: "1px solid #edf2f8",
            borderBottom: "0px",
            width: "300px",
            marginLeft: "20px",
            backgroundPosition: "center"
          }}
        >
          hello world
        </div>
      )}
      <button type="button" onClick={() => setDisplay(true)}>
        Reply
      </button>
    </div>
  );
}

Edit hide-show-state-of-div-react

Related