Good morning, everyone.
I need to create an event just to toggle a class, but I’m not sure if the way CSS handles it works the same way for JS selectors.
Example below:
import React from 'react';
class ToggleClassComponent extends React.Component {
componentDidMount() {
document.addEventListener('DOMContentLoaded', () => {
const triggerElement = document.querySelector('.vtex-rich-text-0-x-paragraph--close-capa-destaque-colecao');
const targetElement = document.querySelector('.vtex-flex-layout-0-x-flexRow--logo-modal-closed-destaque');
console.log(triggerElement)
const handleClick = () => {
if (targetElement) {
targetElement.classList.toggle('vtex-flex-layout-0-x-flexRow--hide--all');
}
};
if (triggerElement) {
triggerElement.addEventListener('click', handleClick);
}
// Cleanup function
return () => {
if (triggerElement) {
triggerElement.removeEventListener('click', handleClick);
}
};
});
}
render() {
return null;
}
}
export default ToggleClassComponent;
@raphaelfelix all good?
I get that a piece of code along those lines would work… you can use the default class dn-s to manage that toggle (I’d recommend adding an observer to always make sure that class exists before running this code).
if what you want is to hide an entire block when a user clicks something, I’d recommend implementing an app that wraps that block in the theme and takes care of the rendering/non-rendering… you’d have better control over it and wouldn’t need to keep manipulating so much in the DOM
Hey, Carlos.
It was just a test block to understand if I should follow the name-app–class format like CSS handles.
In the end, nothing is happening even after adding a click event to this class and logging to the console.
About encapsulation, can you send me a basic example?
I did something like this using trigger layout, but when clicking on element A, it shows element B and element A becomes hidden, and vice versa.
Cheers
I managed to do it with the snippet below, though there’s still a hurdle, since that’s not all I need. Still, it was a ray of light. Cheers
const [isHidden, setIsHidden] = useState(true);
const toggleClass = () => {
setIsHidden(!isHidden);
};
<button className={`destaque-da-colecao-closed ${isHidden ? "hide--all" : ""}`} onClick={toggleClass}>Close</button>
<div className={`destaque-da-colecao ${isHidden ? "" : "hide--all"}`}>
<button id="toggle-destaque" onClick={toggleClass}>X</button>
</div>