Home > Web Front-end > JS Tutorial > body text

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

Mary-Kate Olsen
Release: 2024-11-06 08:32:02
Original
690 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!