Reputation: 973
i am using a functional component, and have created a sidebar menu structure , with parent child way (kind of dropdown). So when I click on parent an active class should be toggle and on its next element toggle style> display> none/block.
<Fragment key={index}>
<button
className='dropdown-btn bg-transparent haschild'
style={{ border: 'none' }}
>
{data.name} <i className='fas fa-chevron-right'></i>
</button>
<div
className='dropdown-container'>
<Content
config={menuItem.children}
children={true}
/>
</div>
</Fragment>
and on use effect
useEffect(() => {
var dropdown = document.getElementsByClassName("haschild");
var i;
for (i = 0; i < dropdown.length; i++) {
dropdown[i].addEventListener("click", function () {
this.classList.toggle("active");
var dropdownContent = this.nextElementSibling;
if (dropdownContent.style.display == "none") {
dropdownContent.style.display = "block";
} else {
dropdownContent.style.display = "none";
}
});
}
},[]);
wherever i have class has child on that element i have to toggle a class active and on its next siblings , want to add style attr with display
Upvotes: 0
Views: 1546
Reputation: 1639
When using a Framework like react that doesn't directly manipulate the DOM it's not recommended to change style like that.
What you should do instead is to either work with classes and toggle them in react, not using document.getElementsByClassName
or similar functions.
This could look something like this, depending on your need:
const ToggleButton = () => {
const [active, setActive] = useState(false);
return (
<button onClick={() => setActive(prev => !prev)} className={active ? 'active' : 'inactive'}>
Toggle active
</button>
);
};
This component would render a button that can be clicked to toggle between the classes active
and inactive
. The rest can and perhaps should be done with purely CSS.
Modern CSS combinators like ~
can be used to affect following elements. You can read more about CSS combinators here
Upvotes: 1