In my react
-app, I have a list of checkboxes/radiobuttons - when checked, I want to add an "selected" or "active"-class to the parent <li>
-tag.
This is my code:
const App = ({data}) => {
const [selected, setSelected] = useState([]);
const changeHandler = (e) => {
setSelected([...selected, e.target.value]);
};
return (
<div>
<ul>
{data.options.map((option) => (
<li key={option.id}>
<div>
<label>
<input
type={data.type === "multiple" ? "checkbox" : "radio"}
name="answer"
id={option.id}
value={option.text}
onChange={(e) => changeHandler(e)}
className="chkbox"
/>
</label>
<h1>
{option.title}
</h1>
</div>
</li>
))}
</ul>
</div>
)
}
My goal is that the DOM looks like this
<ul>
<li >*...some option*</li> // checked
<li>*...some option*</li>
<li>*...some option*</li>
<li >*...some option*</li> // checked
<li>*...some option*</li>
</ul>
so how can I achieve that?
CodePudding user response:
Perhaps you could add an id to the li tag of option.id
and then on changeHandler
use document.getElementById(option.id)
to get the li element and add the selected
class to it.
But I think a better approach would be to create a useState variable that stores an object with all the option.id's and add something like <li key={option.id} className={optionsObj[option.id] && 'active'}>
CodePudding user response:
With React I prefer to avoid any "direct contact" with the actual DOM and keep using the React DOM. Why not you use something like a "state" variable?
<li class={stateVariable}> ... some option </li>
In this way, the styling will depend on the value kept at the stateVariable that could be "selected". Since in the future you might get involved with phone apps, I will suggest you to also learn about styling using objects.