React toggle class
Hi, if we want to open, close or show, not show some DOM element we can do this with a react local state, one handle method, a ternary condition and finally the CSS class.
Here the code:
// Dependencies
import React, { useState } from 'react'; // React hooks
// Styles
import './toggle.css';
// Toggle component
const Toggle = () => {
// Local state
const [open, setOpen] = useState(false);
// Method to handle open/close
const handleToggle = () => {
// Everytime that user click change false to true,
// or true to false.
setOpen(!open);
}
return (
<section className="container">
{ /* This method is executed
everytime that user click the button*/}
<button
type="button"
onClick={handleToggle}
>Toggle</button>
{/* Ternary condition - Keep the close class but
if open state is true insert block class,
if is false do not insert
*/}
<section className={`close ${open ? `block` : ''}`}>
<h2>Im a block</h2>
</section>
</section>
)
}
export default Toggle;
.container {
display: flex;
flex-direction: column;
width: 100%;
height: auto;
align-items: center;
justify-content: center;
}
button {
box-shadow: 0px 0px 0px 2px #9fb4f2;
background-color:#7892c2;
border-radius:10px;
border:1px solid #4e6096;
display:inline-block;
cursor:pointer;
color:#ffffff;
font-family:Arial;
font-size:19px;
padding:12px 37px;
text-decoration:none;
text-shadow:0px 1px 0px #283966;
margin-bottom: 15px;
}
.close {
display: none;
}
.block {
display: block;
width: 300px;
height: 200px;
background-color: #0d2a94;
border: 2 px solid grey;
color: white;
}
Main view:
When user click:
Check the repo here
Criss