Categories
React Answers

How to Add the CSS display: none Style within a Conditional Expression with React?

Spread the love

Sometimes, we want to add the CSS display: none style within a conditional expression with React.

In this article, we’ll look at how to add the CSS display: none style within a conditional expression with React.

Add the CSS display: none Style within a Conditional Expression with React

To add the CSS display: none style within a conditional expression with React, we can pass in an object into the style prop of an element.

For instance, we can 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={{ display: show ? "block" : "none" }}>hello</div>
    </div>
  );
}

We have the show state that we create with the useState hook.

Then we set the onClick prop of the button to a function that calls setShow to toggle show between true and false .

And then we can set the display CSS property of the div with a ternary expression.

If show is true , then set it to 'block' .

Otherwise, we set it to 'none' .

Conclusion

To add the CSS display: none style within a conditional expression with React, we can pass in an object into the style prop of an element.

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 *