I am creating a component in React which includes a checkbox. I want it to toggle back and forth (on and off) and save the state in local storage so if I go to another page, the toggle will be set to what it was before.
Note: I am not using React 16 and can not use state hooks
I created my component and added the ComponentDidMount
and ComponentDidUpdate
functions as below.
import * as React from "react";
import { Checkbox } from 'semantic-ui-react'
type Props = {
label : string
}
type State = {
status: boolean
}
class ChangeOrder extends React.Component<Props, State> {
constructor(props) {
super(props);
this.state = {
status: false
}
}
componentDidMount() {
localStorage.getItem('status') && this.setState({
status: JSON.parse(localStorage.getItem('status'))
})
}
componentDidUpdate(nextProps, nextState) {
localStorage.setItem('status', JSON.stringify(nextState.status));
}
render() {
return (
<Checkbox
onClick={() => this.setState({ status: !status })}
label={this.props.label}
toggle
/>
);
}
}
export default ChangeOrder;
The checkbox works but it does not save the state.
When I right click to inspect and go to Application
and navigate to LocalStorage
, I see the value of the toggle switch go from false to true but clicking it again does not return it to false.
I want to be able to save and persist the toggle button state between true and false.
You just need to set the status on click event from the state to be this.state.status
, pass the status
value to checked
prop to ensure the input has the expected value. Also, I prefer not to use stringify the boolean values instead, evaluate the string boolean value to boolean type. I built an app to check out on codesandbox.