Home  >  Article  >  Web Front-end  >  How to Show or Hide an Element in React with Native Features?

How to Show or Hide an Element in React with Native Features?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-06 08:32:02695browse

How to Show or Hide an Element in React with Native Features?

Show or Hide Element in React

Question

While experimenting with React.js, a user encounters difficulty in displaying or hiding an element on a page via clicking. They request a native React library solution without relying on external libraries.

Answer

React circa 2020

Leveraging React's state hook, we can update the component's state in the onClick callback:

<code class="javascript">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>
  );
};</code>

React circa 2016

Using React's legacy API:

<code class="javascript">var Search = React.createClass({
  getDefaultProps() {
    return { resultsHidden: true };
  },
  handleClick: function () {
    this.setState({ resultsHidden: false });
  },
  render: function () {
    return (
      <div className="date-range">
        <input type="submit" value="Search" onClick={this.handleClick} />
        { !this.props.resultsHidden ? <Results /> : null }
      </div>
    );
  }
});</code>

The above is the detailed content of How to Show or Hide an Element in React with Native Features?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn