Home >Web Front-end >JS Tutorial >How to Dynamically Show or Hide Elements in React Using State?
Beginners often face difficulties in displaying or concealing elements in React using click events. This guide provides a native React solution, eliminating the need for external libraries.
Consider the following React code:
<code class="js">var Search = React.createClass({ handleClick: function (event) { console.log(this.prop); }, render: function () { return ( <div className="date-range"> <input type="submit" value="Search" onClick={this.handleClick} /> </div> ); }, }); var Results = React.createClass({ render: function () { return ( <div id="results" className="search-results"> Some Results </div> ); }, }); React.renderComponent(<Search />, document.body);</code>
Using the latest React features, the solution involves:
Leverage React's state hooks to handle the toggle between showing and hiding the element. State management determines whether the element should be rendered or not.
<code class="js">const Search = () => { // Initialize state to hide results const [showResults, setShowResults] = React.useState(false); // Toggle results visibility on click const onClick = () => setShowResults(true); return ( <div> <input type="submit" value="Search" onClick={onClick} /> { showResults ? <Results /> : null } </div> ); }; const Results = () => ( <div id="results" className="search-results"> Some Results </div> ); // Render the component ReactDOM.render(<Search />, document.getElementById('container'));</code>
The above is the detailed content of How to Dynamically Show or Hide Elements in React Using State?. For more information, please follow other related articles on the PHP Chinese website!