Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
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;
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

It addresses your problems.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!