29
loading...
This website collects cookies to deliver better user experience
Collapsible
. It will return some HTML elements, which will structure our layout.div
element, which will keep all the elements bellow;button
element, responsible for toggling the content visibility;div
element, which will handle our content.import React from "react";
import "./styles.css";
const Collapsible = ({ children, label }) => {
return (
<div className="container">
<button className='toggle'>{label}</button>
<div>{children}</div>
</div>
);
};
export default Collapsible;
.content {
width: auto;
height: auto;
margin-top: 10px;
border: 1px solid #686868;
display: none;
justify-content: center;
border-radius: 10px;
}
.show {
display: flex;
}
display
property. When the div has the .show
class, the content will be displayed!false
.import React, {useState} from 'react'
import './styles.css'
const Collapsible = ({children, label}) => {
const [isOpen, setIsOpen] = useState(false)
onClick
event in the button, let's pass a simple arrow function, setting the isOpen
true or false, according to its previous state (if isOpen === false
, set to true
and vice-versa), using !, the logical "not" operator in javascript. See it:<button className='toggle' onClick={() => setIsOpen(!isOpen)}>{label}</button>
<div className={isOpen ? 'content show' : 'content'}>{children}</div>
<Collapsible label='Click Here'>
<ul>
<li>Profile</li>
<li>Dashboard</li>
<li>Logout</li>
</ul>
</Collapsible>
<Collapsible label='Animals'>
<ul>
<li>Cat</li>
<li>Dog</li>
<li>Cow</li>
</ul>
</Collapsible>