I am trying when I click on a checkbox it should get selected and save its value true in localstorage so that if the page is refreshed it should get value from the localstorage, similarly for second checkbox if it is selected too then also save its value true in localstorage.
In simple way if I select a both the checkboxes it should retain even after page refresh this is what I am trying for
Here is my code is what I have tried
Link - https://codesandbox.io/s/musing-architecture-p2nrg?file=/src/App.js:0-1760
import React from "react";
import "./styles.css";
import { Form } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
export default function App() {
const data = {
naming: localStorage.getItem("naming") || false,
fullname: localStorage.getItem("fullname") || false
};
const [currentCheckboxId, setCheckboxId] = React.useState(data);
const setCheckbox = event => {
const naming = event.target.checked;
console.log(naming);
localStorage.setItem("naming", naming);
setCheckboxId({
...data,
naming: event.target.checked
});
};
const setCheckbox2 = event => {
const fullname = event.target.checked;
console.log(fullname);
localStorage.setItem("fullname", fullname);
setCheckboxId({
...data,
fullname: event.target.checked
});
};
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<Form>
<>
<Form.Check
onChange={setCheckbox}
type="checkbox"
label="Check me out"
id="first"
checked={currentCheckboxId.naming}
/>
<Form.Group controlId="email">
<Form.Label>Email Address</Form.Label>
<Form.Control type="text" placeholder="Enter email" />
</Form.Group>
</>
<>
<Form.Check
onChange={setCheckbox2}
type="checkbox"
label="Check me out"
id="second"
checked={currentCheckboxId.fullname}
/>
<Form.Group controlId="fullname">
<Form.Label>Name</Form.Label>
<Form.Control type="text" placeholder="Enter name" />
</Form.Group>
</>
</Form>
</div>
);
}