import React, { useState } from 'react';
const Component = () => {
const [show, setShow] = useState(false);
return(
<>
<button onClick={() => setShow(prev => !prev)}>Click</button>
{show && <Box>This is your component</Box>}
</>
);
}
export default Component
React circa 2020
In the onClick callback, call the state hook's setter function to update the state and re-render:
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>
)
}
const Results = () => (
<div id="results" className="search-results">
Some Results
</div>
)
ReactDOM.render(<Search />, document.querySelector("#container"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
return(
<nav className="nav__bar">
<ul className="menu">
<li className="menu__icon" onClick={() => setShow(currentShow => !currentShow)}>
<box-icon name='menu' color="floralwhite" size="md"/>
{ show ? <Curtain/> : null }
</li>
</ul>
</nav>
);
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>
)
}
const Results = () => (
<div id="results" className="search-results">
Some Results
</div>
)
ReactDOM.render(<Search />, document.querySelector("#container"))
{ this.state.showMyComponent ? <MyComponent /> : null }
{ this.state.showMyComponent && <MyComponent /> }
In in package.json (Windows)
"scripts": {
...
"cleanBuild": "rimraf ./build/*",
"build": "npm run cleanBuild && set "GENERATE_SOURCEMAP=false" && react-scripts build ",