Home > Article > Web Front-end > How to Show or Hide an Element in React with Native Features?
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.
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>
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!