1React circa 2020
2In the onClick callback, call the state hook's setter function to update the state and re-render:
3
4const Search = () => {
5 const [showResults, setShowResults] = React.useState(false)
6 const onClick = () => setShowResults(true)
7 return (
8 <div>
9 <input type="submit" value="Search" onClick={onClick} />
10 { showResults ? <Results /> : null }
11 </div>
12 )
13}
14
15const Results = () => (
16 <div id="results" className="search-results">
17 Some Results
18 </div>
19)
20
21ReactDOM.render(<Search />, document.querySelector("#container"))
22<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
23<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
24
25<div id="container">
26 <!-- This element's contents will be replaced with your component. -->
27</div>
1import React, { useState } from 'react';
2
3const Component = () => {
4 const [show, setShow] = useState(false);
5 return(
6 <>
7 <button onClick={() => setShow(prev => !prev)}>Click</button>
8 {show && <Box>This is your component</Box>}
9 </>
10 );
11}
12
13export default Component
14
1const Search = () => {
2 const [showResults, setShowResults] = React.useState(false)
3 const onClick = () => setShowResults(true)
4 return (
5 <div>
6 <input type="submit" value="Search" onClick={onClick} />
7 { showResults ? <Results /> : null }
8 </div>
9 )
10}
11
12const Results = () => (
13 <div id="results" className="search-results">
14 Some Results
15 </div>
16)
17
18ReactDOM.render(<Search />, document.querySelector("#container"))