Skip to content

Commit

Permalink
fix: refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
CBID2 committed Oct 28, 2024
1 parent 0a8029b commit fb03f4c
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 14 deletions.
38 changes: 24 additions & 14 deletions animata/button/form-control-switch.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,5 @@
import React, { useState } from "react";
export default function FormControlSwitch() {
const [isOn, setIsOn] = useState(false);
const toggleSwitch = () => {
setIsOn(!isOn);
};
return (
<button onClick={toggleSwitch} style={{ backgroundColor: isOn ? "green" : "red" }}>
<div style={{ ...styles.switch, backgroundColor: isOn ? "green" : "grey" }}>
{isOn ? "✔️" : "❌"}
</div>
</button>
);
}
import { useState } from "react";

const styles = {
switch: {
width: 40,
Expand All @@ -28,3 +16,25 @@ const styles = {
margin: 4,
},
};

interface ToggleSwitchProps {
onChange: (value: boolean) => void;
defaultChecked?: boolean;
}
function FormControlSwitch({ onChange, defaultChecked }: ToggleSwitchProps) {
const [isOn, setIsOn] = useState(defaultChecked ?? false);
const handleToggleSwitch = () => {
const newCheckedState = !isOn;
setIsOn(newCheckedState);
onChange?.(newCheckedState);
};
return (
<button onClick={handleToggleSwitch} style={{ backgroundColor: isOn ? "green" : "white" }}>
<div key="switch" style={{ ...styles.switch, backgroundColor: isOn ? "green" : "grey" }}>
{isOn ? "✔️" : "❌"}
</div>
</button>
);
}

export { FormControlSwitch };
43 changes: 43 additions & 0 deletions button/form-control-switch.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { useState } from "react";

const switchStyles = {
switch: {
width: 40,
height: 40,
borderRadius: 20,
display: "flex",
justifyContent: "center",
alignItems: "center",
transition: "background-color 0.3s ease",
cursor: "pointer",
border: "none",
outline: "none",
padding: 8,
margin: 4,
},
};

interface FormControlSwitchProps {
onChange: (value: boolean) => void;
defaultChecked?: boolean;
}

function FormControlSwitch({ onChange, defaultChecked }: FormControlSwitchProps) {
const [isOn, setIsOn] = useState(defaultChecked ?? false);

const toggleSwitch = () => {
const newCheckedState = !isOn;
setIsOn(newCheckedState);
onChange?.(newCheckedState);
};

return (
<button onClick={toggleSwitch}>
<div style={{ ...switchStyles.switch, backgroundColor: isOn ? "green" : "grey" }}>
{isOn ? "✔️" : "❌"}
</div>
</button>
);
}

export { FormControlSwitch };

0 comments on commit fb03f4c

Please sign in to comment.