Search code examples
javascriptreactjsreact-hooksevent-listener

How to get button to change visibility based on checkbox in JavaScript


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


Solution

  • Another variation of what @The KNVB already said:

    const [visible, setVisible] = useState(false);
    
    return (
        <div>
            <input type="checkbox" onClick={() => setVisible(!visible)}/>
            <br />
            { visible && <button>visible button</button> } 
        </div>
    )