get customized attributes value from switch toggle

Viewed 34

I am trying to get value of the attribute 'data-id'. But when i try to get the value of 'data-id' from onchange eventhandler. I am getting a null value.

 function handleChange(event, e, id) {
            const currentID = e.target.getAttribute('data-id');
}

return(
settings.map(item => {
                    return (
                        <div>
                                <div>
                                    <Switch
                                        checked={item.value}
                                        color="primary"
                                        name="checkedB"
                                        inputProps={{ "aria-label": "primary checkbox" }}
                                        onChange={(event, e) => handleChange(event, e, item.ltbAppSettingID)}
                                        id={"firmSwitch-"+item.settingName}
                                        data-id={item.settingName}
                                    />
                                    <label class="checkLabel" htmlFor={item.ltbAppSettingID}>

                                        <span>{item.name}</span>
                                    </label>
                                </div>
                            }
)
1 Answers

As per the MDN docs, the onchange global handler accepts one and only argument, which is the event. You give it two (event, and e).

Try replacing with that:

 function handleChange(e, id) {
            const currentID = e.target.getAttribute('data-id');
}

return(
settings.map(item => {
                    return (
                        <div>
                                <div>
                                    <Switch
                                        checked={item.value}
                                        color="primary"
                                        name="checkedB"
                                        inputProps={{ "aria-label": "primary checkbox" }}
                                        onChange={(e) => handleChange(e, item.ltbAppSettingID)}
                                        id={"firmSwitch-"+item.settingName}
                                        data-id={item.settingName}
                                    />
                                    <label class="checkLabel" htmlFor={item.ltbAppSettingID}>

                                        <span>{item.name}</span>
                                    </label>
                                </div>
                            }
)

EDIT: didn't realize it was a MaterialUI Switch Component

As you can see from the link, you can't just add any attribute to these components like you would with vanilla JS. If you have to retrieve it for some reason, I'm afraid you'll have to store it elsewhere.

Related