vendredi 17 février 2023

Correct way of updating checkbox with keyboard press in React

I've got the following code:

export default function Tag(props: { tag: ITag, setTag: (tag: string) => void }) {
    const [checked, setChecked] = useState(false)

    const handleTagChange = () => {
        props.setTag(props.tag.abbreviation);
        var element = document.getElementById(props.tag.abbreviation);
        if (!checked) {
            element?.classList.add("label-toggle")
        }
        else {
            element?.classList.remove("label-toggle")
        }
        setChecked(!checked)
    }

    return (
        <div id={props.tag.abbreviation} className='label-button' onClick={handleTagChange}>
            <input id='check' key={props.tag.hotkey} checked={checked} onChange={handleTagChange} type="checkbox" />
            <div className='label-title'>{props.tag.abbreviation}</div>
            <div className='label-icon' style=></div>
            <div className='label-hotkey'>{props.tag.hotkey}</div>
        </div>
        
    )

Everything works as expected if I use mouse click to trigger the checkbox. It works both if I press on the checkbox or the surrounding div with function handleTagChange()

I've added a key listener, so that the checkbox can be triggered with a keyboard key press.

const handleHotKey = (e: KeyboardEvent) => {
    if (e.key == props.tag.hotkey) {
        handleTagChange();
    }
}

useEffect(() => {
    document.addEventListener('keydown', e => { handleHotKey(e) }, false)
}, [])

Key listener works, key press is detected, however the value of the checked state simply does not update.

I have no clue what I'm doing wrong. What is the correct way to achieve this?

Thanks.




Aucun commentaire:

Enregistrer un commentaire