Home >Web Front-end >JS Tutorial >How to Toggle Element Visibility in React?

How to Toggle Element Visibility in React?

Linda Hamilton
Linda HamiltonOriginal
2024-11-06 01:29:021052browse

How to Toggle Element Visibility in React?

Show or Hide Element in React

In a React application, you often need to show or hide elements based on user interaction. Let's explore how to achieve this using native React functionality.

var Search= React.createClass({</p>
<pre class="brush:php;toolbar:false">handleClick: function (event) {
    console.log(this.prop);
},
render: function () {
    return (
        <div className=&quot;date-range&quot;>
            <input type=&quot;submit&quot; value=&quot;Search&quot; onClick={this.handleClick} />
        </div>
    );
}

});

var Results = React.createClass({

render: function () {
    return (
        <div id=&quot;results&quot; className=&quot;search-results&quot;>
            Some Results
        </div>
    );
}

});

React.renderComponent( , document.body);

In this example:

  • Search component renders a button that triggers the handleClick method.
  • Results component represents the element we want to toggle.

Toggle Element State

To toggle element visibility, we need to maintain state. In modern versions of React, we can use the useState hook to manage component state:

const Search = () => {<br>  const [showResults, setShowResults] = useState(false)<br>  const handleClick = () => setShowResults(true)<br>  return (</p>
<pre class="brush:php;toolbar:false"><div>
  <input type="submit" value="Search" onClick={handleClick} />
  { showResults ? <Results /> : null }
</div>

)
}

const Results = () => (

Some Results


)

ReactDOM.render(, document.querySelector("#container"))

Here:

  • useState initializes a state variable (showResults) with an initial value (false).
  • setShowResults is a function that updates the showResults state, triggering a re-render.
  • When the button is clicked, handleClick sets showResults to true, rendering the Results component.

This approach provides a native and efficient way to show or hide elements in React applications.

The above is the detailed content of How to Toggle Element Visibility in React?. 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