vendredi 18 juin 2021

Cannot change visibility settings with onChange event in React app

In my React app component, I have a table with checkboxes. Below the table is a card that I want to display information based on the selected/clicked row. On load, its visibility is set to hidden.

<div className="card text-center" id="profileCard" style=>
...
</div>

I have added a function for the onChange event to display the card information based on the row that is checked.

const IndeterminateCheckbox = React.forwardRef(
    //This is the function for the checkboxes in page select
    ({ indeterminate, ...rest }, ref) => {
        const defaultRef = React.useRef()
        const resolvedRef = ref || defaultRef

        React.useEffect(() => {
            resolvedRef.current.indeterminate = indeterminate
        }, [resolvedRef, indeterminate])
        return (
            <>
                <input type="checkbox" ref={resolvedRef} {...rest} />
            </>
        )
    }
 )
  ....
 <div>
     <IndeterminateCheckbox {...row.getToggleRowSelectedProps()} onChange={(e) => {
                            e.preventDefault();
                            showCard(e);}}
     />
 </div>

 ...
 
 const showCard = (e) => {
    if (e.target.checked) {
        document.getElementById("profileCard").visibility = "visible";
        e.preventDefault();
    } else {
        document.getElementById("profileCard").visibility = "hidden";
        e.preventDefault();
    }
};

What currently happens is that the box is checked, it goes into the showCard function and then sets the visibility of the element to "visible" (if I console.log() it in the debugger, it shows the changed visibility). But as soon as it comes out of the function, the checked box disappears and the card never displays as if the page has been completely reset. I have tried to add e.preventDefault() to fix this, but that doesn't seem to work. Any idea as to what I am doing incorrectly here or how to resolve this issue?

NOTE: I only included the relevant parts of the code to keep the focus on this one problem.




Aucun commentaire:

Enregistrer un commentaire