I have a task that is simple (one line) in plain HTML/CSS/JS, but I can’t find a simple and working method in React.
I have a parent div, and it has two children. The second child is the meaningful content. The first child is a “hide” button, that, when clicked, hides the parent div (including, of course, both child divs).
function SecondPage({ thisData }) {
function hidePage(thisID) {
let thisElement = document.getElementById(thisID)
thisElement.style.display='none';
}
return ( <>
<div className="page" id="InfoPage">
<div className="hidePageButton" onClick={hidePage("InfoPage")}>
✖
</div>
<div className="pageContent">
Some text and stuff
</div>
</div>
);
}
In fact, there is an even easier/simpler way using onClick={hidePage(this)}
and function hidePage(el) {el.parentNode.style.display='none'
}
But these methods don’t work in React. I’ve seen some proposed solutions for React that supposedly do what I want, but they are complicated. They propose defining classes with embedded functions and all kinds of seemingly extra baggage to do this simple task.
I’ve also read hints that being able to get elements by IDs and getting parents is not in line with React’s philosophy. But I don’t care about that. I don’t need the best way according to React gospel, or the most modular, or the safest, or anything like that. But I also prefer not to install some extra package that provides this functionality, because that may not be robust or work properly in the future, but I’ll consider it if it’s a really strongly supported package.
I understand that I probably have to use useState
and useEffect
to get this to work. Create a toggle variable that holds the visible status, and use that variable in a conditional statement that determines whether to show the page or show null. Then onClick I change the value of the toggle, which changes the rendering of the page. I found some examples similar to that, but not a minimal example that worked in React.
What is the simplest possible way to get a div button to hide its parent div (or make other style changes) on click in React (jsx).