Categories
React Answers

How to handle visibility=hidden with React?

Spread the love

Sometimes, we want to handle visibility=hidden with React.

In this article, we’ll look at how to handle visibility=hidden with React.

How to handle visibility=hidden with React?

To handle visibility=hidden with React, we can set the visibility CSS property in the style prop object.

For instance, we write:

import React, { useState } from "react";

export default function App() {
  const [show, setShow] = useState(true);

  return (
    <div>
      <button onClick={() => setShow((s) => !s)}>toggle</button>
      <div style={{ visibility: show ? "visible" : "hidden" }}>hello world</div>
    </div>
  );
}

to add a div that can be toggled by the button.

We define the show state with the useState hook.

Then we add a button that has the onClick prop set to a function that calls setShow to toggle the value of show.

Next, we add a div that has the style prop with the visibility property set to 'visible' if show is true and 'hidden' otherwise.

As a result, when we click on toggle, we’ll see the div being toggled on and off.

Conclusion

To handle visibility=hidden with React, we can set the visibility CSS property in the style prop object.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *