Skip to content
Advertisement

Display value of slider with respect to slider thumb react native

I want to move the label with respect to slider thumb just like this one: enter image description here

Right now my slider is like this:

enter image description here

I want to display the label shown as 30 km with respect to the slider thumb such that as the slider moves, the label should move accordingly.

I am using Native React Slider component.

this is my code:

<Slider 
     style={styles.slider} 
     thumbTintColor='rgb(252, 228, 149)' 
     step={1} 
     maximumValue={5} 
     thumbTintColor='rgb(252, 228, 149)' 
     maximumTrackTintColor='#494A48' 
     minimumTrackTintColor='rgb(252, 228, 149)' />

Advertisement

Answer

Solution to your problem:

    constructor(props){
        super(props)
        this.state = {
            distance: 30,
            minDistance: 10,
            maxDistance: 100
        }
    }


    render() {
        return (
            <View style={styles.container}>
                <Slider
                    style={{ width: 300}}
                    step={1}
                    minimumValue={this.state.minDistance}
                    maximumValue={this.state.maxDistance}
                    value={this.state.distance}
                    onValueChange={val => this.setState({ distance: val })}
                    thumbTintColor='rgb(252, 228, 149)'
                    maximumTrackTintColor='#d3d3d3' 
                    minimumTrackTintColor='rgb(252, 228, 149)'
                />
                <View style={styles.textCon}>
                    <Text style={styles.colorGrey}>{this.state.minDistance} km</Text>
                    <Text style={styles.colorYellow}>
                        {this.state.distance + 'km'}
                    </Text>
                    <Text style={styles.colorGrey}>{this.state.maxDistance} km</Text>
                </View>
            </View>
        );
    }
}

Styles:

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#000',
    },
    textCon: {
        width: 320,
        flexDirection: 'row',
        justifyContent: 'space-between'
    },
    colorGrey: {
        color: '#d3d3d3'
    },
    colorYellow: {
        color: 'rgb(252, 228, 149)'
    }
});

Output:

https://i.stack.imgur.com/telTT.jpg

Working Snippet: https://snack.expo.io/Syrt3Bs7z

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement