Search code examples
javascriptcssreactjslocal-storagestyles

React Local Storage to target previously selected buttons


Each button changes color when pressed. And I want them to stay that color every time the page reloads until a a localStorage.clear() is ran. So I'm trying to re-apply the previously applied css with local storage. My idea is to store the Ids of each button, loop through Ids, and re-apply css. But it keeps throwing error: "Cannot read properties of null (reading 'style')". Another issue I seem to have is I lose my local storage on the 2nd page reload! If you have a way to improve this or a better way to go about this please let me know! Thanks.

UPDATED Code
Here is a link to the most working version https://codesandbox.io/s/festive-rui-vz7tf?file=/src/App.js I added a "Delete History Btn". The only issue now is after a reload and selecting another button, the local storage is completely erased with the new selection. What I need is the selections to stack until the user runs a localStorage.clear().

import React,{useState,useEffect} from 'react';


      const App=()=> {
  const [btns, setBtns] = useState([]);

  useEffect(() => {
    localStorage.setItem('BtnsClicked', JSON.stringify({ btns }));
  }, [btns]);


  const handleAcknowledge=(event)=>{
    setBtns([...btns, event.target.id])
  
    event.target.style.backgroundColor = "red"
    event.target.innerHTML = "Clicked!"
  }

  const reSelectBtns=()=>{
    const storedBtns = JSON.parse(localStorage.getItem('BtnsClicked'));
    
    if (storedBtns.btns.length){
      storedBtns.btns.forEach(btn=>{
        console.log(document.getElementById(btn).style.backgroundColor = "red")
    })
  }
  }
  reSelectBtns()

  return (
    <div className="App">
     
      <button id = "1" onClick={handleAcknowledge}>Acknowledge</button> 
      <button id = "2" onClick={handleAcknowledge}>Acknowledge</button> 
      <button id = "3" onClick={handleAcknowledge}>Acknowledge</button>  
      <button id = "4" onClick={handleAcknowledge}>Acknowledge</button>  
      
    </div>
  );
}

export default App;

Solution

  • Checkout this sandbox link of mine https://codesandbox.io/s/blissful-marco-7wgon?file=/src/App.js

    It addresses your problems.