I currently have a function that simply grabs all the checkboxes with the same class element and then console logs only the first one. I am trying to simply console log the name of that checkbox that I set, but it does not seem to be working.
It does however console log the style or className when I try it, but not just the name.
Code:
const handleAddColorCheckbox = (checkbox)=>{
const checkboxs1 = document.querySelectorAll('.addnote-color')
console.log(checkboxs1[0].style)
}
<input type='checkbox' name='addnote-color-white'/>
<span className='addnote-color pointer' name='white' style={{'--addnote-color-selector': '#ffffff'}}/>
CodePudding user response:
If what you're looking for is getting this inline style and the name, here's a solution using querySelectorAll(I'm not sure why you chose to use that though)
console.log(checkboxs1[0].attributes[2].value);
console.log(checkboxs1[0].attributes[1].value);
First line will print the inline style which is the third attribute. Second line will print the name, which is the second attribute.
CodePudding user response:
You can either attach a listener to each checkbox or, similarly to vanilla JS, you can use a form of event delegation* by attaching one listener to a parent component and catching events from its children.
*React uses a synthetic events system whereby all events are attached to the document root rather than individual nodes. So really everything is delegated - you just don't notice it.
Here's a simplified example that has a listener on a parent component that catches events from its children. When it catches one it calls the handler which determines whether the element was a checkbox, and then logs its name.
const { useState } = React;
function Example() {
function handleClick(e) {
if (e.target.matches('[type="checkbox"]')) {
const { name } = e.target;
console.log(name);
}
}
return (
<section onClick={handleClick}>
<input type="checkbox" name="addnote-color-red" />
<input type="checkbox" name="addnote-color-white" />
<input type="checkbox" name="addnote-color-blue" />
</section>
);
}
ReactDOM.render(
<Example />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Additional documentation