I'm fairly new to react and I'm working on a project where I want to highlight (change the css classname) of any of these list items on click shown in the picture above.
I've looked on stack and online and can't find anything that is working for me.
This is what I've done so far, when I use this the CSS doesn't change and I get an error in the console log saying : "Uncaught TypeError: Cannot set properties of null (setting 'onclick')"
Any help or pointers would be appreciated, below is the code
React Code
//I just kept in what I'm attempting
const [changeStyle1, setChangeStyle1] = useState(false);
const changeLiStyle = () => {
setChangeStyle1(true);
}
return (
<div>
<ul className='editElectrodeBox'>
<li className={changeStyle1 ? 'electrodeBoxItem selector' : 'electrodeBoxItem'} onClick={changeLiStyle} id='elementOne'>Magnesium</li>
The CSS
.editElectrodeBox {
height: 35vh;
list-style: none;
overflow-y: scroll;
background-image: linear-gradient(to left, rgb(162, 234, 142) , rgb(118, 203, 240));
}
.electrodeBoxItem {
padding: 20px;
cursor: pointer
}
.selected {
background-image: linear-gradient(135deg, #f34079 40%, #fc894d);
color: whitesmoke;
}
CodePudding user response:
I believe the issue is calling the incorrect className
So I would change selector to selected
<li className={changeStyle1 ? 'electrodeBoxItem selected' : 'electrodeBoxItem'} onClick={changeLiStyle} id='elementOne'>Magnesium</li>
instead of
<li className={changeStyle1 ? 'electrodeBoxItem selector' : 'electrodeBoxItem'} onClick={changeLiStyle} id='elementOne'>Magnesium</li>