I am trying to have my toggle switch persist its state upon a page refresh in React.JS. I have looked into local storage but I am not sure how to implement it correctly.
Currently, I am creating a toggle switch in semantic and adding it as a component in my subheader.
This is my toggle switch component
import * as React from "react";
import { Checkbox } from 'semantic-ui-react'
type Props = {
label : string
}
class ToggleSwitch extends React.Component<Props> {
state = { status: false }
render() {
return (
<Checkbox
onClick={() => this.setState({ status: !status })}
label={this.props.label}
toggle
/>
);
}
}
export default ToggleSwitch;
This is my subheader class where I am calling the component
import * as React from "react";
import ToggleSwitch from './new_layout/ToggleSwitch'
interface Props {
name: string;
renderAction?: () => any;
}
const SubHeader: React.SFC<Props> = ({ name, renderAction }) => {
return (
<div className="settings-submenu">
<div className="settings-submenu-name">{name}</div>
<div className="settings-submenu-name">{renderAction && renderAction()}</div>
<ToggleSwitch label = "Enable New Layout"/>
</div>
);
};
export default SubHeader;
I think you can achieve it by:
Here:
import React, { useEffect, useState } from "react";
import { Checkbox } from "semantic-ui-react";
type Props = {
label: string;
};
function ToggleSwitch(props: Props) {
const [toggle, setToggle] = useState(false);
useEffect(() => {
// check when the component is loaded
const localStorageToggled = localStorage.getItem("toggled");
// If is not null
if (localStorageToggled) {
setToggle(localStorageToggled === "true" ? true : false);
} else {
// If null set the localStorage key/value as a string.
localStorage.setItem("toggle", `${toggle}`);
}
}, []);
const handleToggle = (toggle: boolean) => {
localStorage.setItem("toggle", `${toggle}`);
setToggle(toggle);
};
return (
<Checkbox
onClick={() => handleToggle(!toggle)}
label={props.label}
toggle
/>
);
}
export default ToggleSwitch;
Link: https://codesandbox.io/s/flamboyant-einstein-jy6h3?file=/src/new_layout/ToggleSwitch.tsx:0-883 Video: https://streamable.com/0nkgub