React toggle to be sain
At this unbearable time, where we bite our tongue not to cry “How didn’t you see this”, I created a React toggle to stay sane.
CSS & React:
const Check = memo(({onChange}) => {
console.log('check render')
const [isOn,setIsOn] = useState(true);
const onInnerChange = ()=>{
setIsOn(!isOn);
onChange(!isOn);
}
return(
<div
className={`checkbox ${isOn && 'on'}`}
onClick={onInnerChange}
onKeyUp={onInnerChange}
tabIndex={0}
>
</div>
);
});
const App = () => {
const [isOn,setIsOn] = useState(true);
const [count,setCount] = useState(1);
const click = useCallback((v)=>{
setIsOn(v);
},[])
return(
<div>
<p>is on: {isOn.toString()}</p>
<Check onChange={click} />
<p onClick={()=>setCount(count+1)}>count: {count}</p>
</div>
);
}
ReactDOM.render(<App />,
document.getElementById("root"))
.checkbox{
display: inline-block;
border: solid 1px #ccc;
border-radius: 16px;
position: relative;
height: 30px;
width: 60px;
&::before{
content: ' ';
display: inline-block;
border: solid 1px blue;
border-radius: 100%;
width: 24px;
height: 24px;
position: absolute;
transition: all 0.5s linear;
top: 2px;
right:32px;
background: gray;
}
&.on::before{
right:2px;
background: green;
}
}
I hope on a brighter day to think of a way to make this responsive.