I am working on adding a value to localstorage with an Onclick event. It is supposed to take the innerHTML from the button and put the value into the local storage as the "Cemetery" value.
I have tried multiple different ways of getting the value but I keep getting undefined. If you could give me a hand and some pointers, that would be great!
const CemeteryPage = () => {
function setCemetery(ListItem) {
localStorage.setItem("Cemetery", ListItem.value)
}
return (
<>
<div className='Header'>
<h1>What <span>cemetery</span> is this stone going to?</h1>
<div className='Line'></div>
</div>
<div class="CemeteryList">
<div className="ListItem" onClick={function(){setCemetery(this)}}>
St Anthony's Cemetery
</div>
<div className="ListItem" onClick={function(){setCemetery(this)}}>
Hillside Cemetery
</div>
</div>
</>
)
}
I tried using .getAttribute, .attributes[], I tried adding a value attribute and pulling it from there but still got undefined.
You tried to pass (this) as an argument to the setCemetery function, which wont work cos that is the entire DOM. The below should work.
const CemeteryPage = () => {
const handleSetCemetry = (cemetery) => {
localStorage.setItem("cemetery", cemetery);
};
return (
<>
<div className="Header">
<h1>
What <span>cemetery</span> is this stone going to?
</h1>
<div className="Line"></div>
</div>
<div className="CemeteryList">
<div
className="ListItem"
onClick={(e) => handleSetCemetry(e.target.innerText)}
>
St Anthony's Cemetery
</div>
<div
className="ListItem"
onClick={(e) => handleSetCemetry(e.target.innerText)}
>
Hillside Cemetery
</div>
</div>
</>
);
};