Home >Web Front-end >JS Tutorial >How to Toggle Element Visibility 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="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(
In this example:
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(
Here:
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!