How to toggle a UI element in React

Intro

To toggle a UI element in React, you can use the useState hook and a conditional statement to change the value of a state variable that determines whether the element is shown or hidden.

Sample code

Here's an example of how you might do this:

import React, { useState } from 'react'
function MyComponent() {
  // Define a state variable called "showUI" with an initial value of "false"
  const [showUI, setShowUI] = useState(false)

  return (
    <div>
      {/* Use a conditional statement to toggle the value of showUI */}
      {showUI ? (
        <p>This is the UI element that will be shown or hidden.</p>
      ) : null}

      <button onClick={() => setShowUI(!showUI)}>Toggle UI</button>
    </div>
  )
}

Explanation

In this example, when the showUI state variable is true, the UI element is shown. When it's false, the UI element is hidden. When the button is clicked, the setShowUI function is called to toggle the value of showUI, which causes the UI element to be shown or hidden.