@amxchange/grid-view-web-client
Version:
amxchange grid view framework web client in react ( a module extracted from existing jax )
104 lines (96 loc) • 3.38 kB
JSX
import React, { useEffect } from "react";
import { styled } from "@mui/material/styles";
import Switch from "@mui/material/Switch";
export const StyledSwitch = styled(Switch)(({ theme }) => ({
width: 60,
height: 40,
padding: 15,
margin: 0,
"& .MuiSwitch-switchBase": {
margin: 0,
padding: 0,
transform: "translateX(1px)",
"&.Mui-checked": {
color: "#fff",
transform: "translateX(80px)",
"& .MuiSwitch-thumb:before": {
backgroundColor: "#006141",
borderRadius: 50
},
"& + .MuiSwitch-track": {
opacity: 0.5,
backgroundColor: "#00b935"
}
}
},
"& .MuiSwitch-thumb": {
backgroundColor: "#006141",
width: 55,
height: 55,
"&:before": {
content: "''",
position: "absolute",
width: "100%",
height: "100%",
left: 0,
top: 0,
backgroundRepeat: "no-repeat",
backgroundPosition: "center",
backgroundColor: "#006141",
borderRadius: 50
}
},
"& .MuiSwitch-track": {
opacity: 0.5,
backgroundColor: "#00b935",
borderRadius: 20 / 2
}
}));
const _Switch = React.forwardRef(
({ label, options, value, onChangeInput, errorMsg, containerClass, ...restProps }, ref) => {
/**
* 1st option would always be Switch-left (i.e, OFF ) and 2nd option would always be Switch-right (i.e, ON )
*/
const off = options[0] || {
label: "Off",
value: "OFF"
};
const on = options[1] || {
label: "On",
value: "ON"
};
useEffect(() => {
if (value === "") {
onChangeInput(off, false); //initial value would be always OFF
}
if (value !== "" && typeof value !== "object" && [on, off].find(opt => value == opt.value)) {
onChangeInput(
[on, off].find(opt => value == opt.value),
false
); //selecting the value that was set before options were populated
}
}, [value]);
const handleChange = e => {
let newVal = e.target.checked;
let _value = newVal === true ? on : off;
onChangeInput(_value);
};
return (
<div className={`input-field-sec switch ${errorMsg ? "error-field" : ""} ${containerClass || ""}`}>
<span className="" style={value?.value === on?.value ? { color: "#858383" } : {}}>
{off?.label}
</span>
<StyledSwitch
sx={{ m: 1, width: 135, height: 60 }}
checked={value?.value === on.value ? true : false}
onChange={handleChange}
/>
<span className="" style={value?.value === on?.value ? {} : { color: "#858383" }}>
{on?.label}
</span>
{errorMsg && <span className="helperTextError">{errorMsg}</span>}
</div>
);
}
);
export default _Switch;