Skip to content

Commit 0c7b439

Browse files
authored
Fix Slider web offset issue (#806)
* Pass in ref to native slider * Revert "Pass in ref to native slider" This reverts commit 9b7c7d2. * Force `onLayout` called twice * Add comment and some clean up
1 parent acb83b8 commit 0c7b439

File tree

1 file changed

+23
-1
lines changed

1 file changed

+23
-1
lines changed

packages/core/src/components/Slider.tsx

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import * as React from "react";
2-
import { View, StyleSheet, StyleProp, ViewStyle } from "react-native";
2+
import { View, StyleSheet, StyleProp, ViewStyle, Platform } from "react-native";
33
import NativeSlider from "@react-native-community/slider";
44
import isNumber from "lodash.isnumber";
55
import toNumber from "lodash.tonumber";
@@ -72,6 +72,26 @@ function Slider({
7272
value || defaultValue
7373
);
7474

75+
/**
76+
* Web version of the slider relies on some logic running in the onLayout callback using a given React ref (https://github.com/callstack/react-native-slider/blob/main/package/src/RNCSliderNativeComponent.web.tsx#L320)
77+
*
78+
* The issue is that the onLayout callback is called before the ref is initialized, which leads to an improperly initiatilzed variable
79+
* that determines the x position of the slider
80+
*
81+
* Similair issue: https://github.com/callstack/react-native-slider/issues/470
82+
*
83+
* This workaround forces onLayout to be called twice, where the 2nd time around the ref is initialized
84+
* Done by updating the style of a child component which forces re layout
85+
*/
86+
const [tempThumbStyle, setTempThumbStyle] = React.useState<ViewStyle>({
87+
width: 0,
88+
height: 0,
89+
});
90+
91+
React.useEffect(() => {
92+
setTempThumbStyle({ width: undefined, height: undefined });
93+
}, []);
94+
7595
React.useEffect(() => {
7696
if (value != null) {
7797
setInternalValue(value);
@@ -114,6 +134,8 @@ function Slider({
114134
thumbTintColor={thumbColor}
115135
onSlidingComplete={handleSlidingComplete}
116136
style={styles.slider}
137+
//@ts-ignore Not registered in types
138+
thumbStyle={Platform.OS === "web" ? tempThumbStyle : undefined}
117139
/>
118140
{rightIcon ? (
119141
<Icon color={rightIconThemeColor} name={rightIcon} size={24} />

0 commit comments

Comments
 (0)