new to JS here and working on a react project, I want to essentially have the button’s visibility attribute which is set to false to change to true when a checkbox is checked, here is my code and I believe the logic is there but for some reason is not reflected on the UI, any advice is appreciated
const [visible, setVisibility] = useState(false)
function clicked() {
console.log('in cliked')
const check = document.getElementById('acknowledged')
check.addEventListener('click', showContinueButton())
setVisibility(true)
}
function showContinueButton() {
const continueButton = document.getElementById('continue')
console.log(continueButton.getAttribute("visibility"))
if(visible) {
console.log('in the visible for loop')
continueButton.setAttribute('visibility', 'visible')
}
}
the code above is the code I have defined before the return JSX, then within the JSX I call this code as followed…
<input type='checkbox' id='acknowledged' onClick={clicked}></input>
So essentially when this checkbox is clicked, using the onClick attribute, I pass the click function I passed earlier which has an eventListener with a callback function to change the visibility of the button
2
Answers
I want to point out that there are a lot of classical JavaScript logic in your functions, which should be used via hooks, and not directly.
Hence these vanilla functions have better alternatives in React.
The right way to resolve your issue should instead be as follows:
Working example here
With the use of a state, you don’t need to manipulate the CSS.
Here is an example for your reference: