Categories
React Answers

How to show or hide element in React?

Spread the love

Sometimes, we want to show or hide element in React.

In this article, we’ll look at how to show or hide element in React.

How to show or hide element in React?

To show or hide element in React, we can check a state before rendering a component.

For instance, we write

const Results = () => (
  <div id="results" className="search-results">
    Results
  </div>
);

const Search = () => {
  const [showResults, setShowResults] = React.useState(false);
  const onClick = () => setShowResults(true);
  return (
    <div>
      <input type="submit" value="Search" onClick={onClick} />
      {showResults ? <Results /> : null}
    </div>
  );
};

to define Search component.

In it, we have the showResulrs state.

We set showResults in the onClick function with setShowResults(true);.

Then we set onClick as the value of the onClick prop to make showResults true when we click the button.

And then Results will show when showResults is true.

Conclusion

To show or hide element in React, we can check a state before rendering a component.

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 *