Skip to content

Commit

Permalink
feat: ⚡ Added memoized callback and value prop to switch component
Browse files Browse the repository at this point in the history
  • Loading branch information
Karthik-B-06 committed Aug 29, 2020
1 parent 6a0e016 commit 50153a5
Showing 1 changed file with 10 additions and 8 deletions.
18 changes: 10 additions & 8 deletions src/Switch/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ const RNSwitch = ({
activeTrackColor,
inActiveTrackColor,
thumbColor,
value,
}) => {
const [switchTranslate] = useState(new Animated.Value(0));
const [on, setOn] = useState(false);
useEffect(() => {
if (on) {
if (value) {
spring(switchTranslate, {
toValue: 21,
mass: 1,
Expand All @@ -33,19 +33,19 @@ const RNSwitch = ({
restDisplacementThreshold: 0.001,
}).start();
}
}, [on, switchTranslate]);
}, [value, switchTranslate]);
const interpolateBackgroundColor = {
backgroundColor: interpolateColors(switchTranslate, {
inputRange: [0, 22],
outputColorRange: [inActiveTrackColor, activeTrackColor],
}),
};
const handlePressAction = () => {
handleOnPress(!on);
setOn(!on);
};
const memoizedOnSwitchPressCallback = React.useCallback(() => {
handleOnPress(!value);
}, [handleOnPress, value]);

return (
<Pressable onPress={handlePressAction}>
<Pressable onPress={memoizedOnSwitchPressCallback}>
<Animated.View
style={[styles.containerStyle, interpolateBackgroundColor]}
>
Expand Down Expand Up @@ -98,12 +98,14 @@ RNSwitch.propTypes = {
activeTrackColor: PropTypes.string,
inActiveTrackColor: PropTypes.string,
thumbColor: PropTypes.string,
value: PropTypes.bool,
};

RNSwitch.defaultProps = {
activeTrackColor: "#007AFF",
inActiveTrackColor: "#F2F5F7",
thumbColor: "#FFF",
value: false,
};

export default RNSwitch;

0 comments on commit 50153a5

Please sign in to comment.