Code Monkey home page Code Monkey logo

react-native-slider's Introduction

@miblanchard/react-native-slider

Node.js CI npm version npm downloads npm licence Platform

A pure JavaScript version of the <Slider> component for react-native and react-native-web. This can be a direct replacement for the Slider component from react-native/@react-native-community. Ideas and contributions are very welcome.

Try it out live on Expo Snack.

Screenshot of Slider options

Install

yarn add @miblanchard/react-native-slider

or

npm i --save @miblanchard/react-native-slider

Version 1.x.x only supports React Native >= 0.59.0

React Native version(s) Supporting react-native-slider version(s)
v0.59.0+ v1.x.x

Usage

import React from 'react';
import {Slider} from '@miblanchard/react-native-slider';
import {AppRegistry, StyleSheet, View, Text} from 'react-native';

class SliderExample extends React.Component {
    state = {
        value: 0.2,
    };

    render() {
        return (
            <View style={styles.container}>
                <Slider
                    value={this.state.value}
                    onValueChange={value => this.setState({value})}
                />
                <Text>Value: {this.state.value}</Text>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginLeft: 10,
        marginRight: 10,
        alignItems: 'stretch',
        justifyContent: 'center',
    },
});

AppRegistry.registerComponent('SliderExample', () => SliderExample);

Props

Prop Type Optional Default Description
animateTransitions bool Yes false Set to true if you want to use the default 'spring' animation
animationConfig object Yes undefined Used to configure the animation parameters. These are the same parameters in the Animated library.
animationType string Yes 'spring | 'timing' Set to 'spring' or 'timing' to use one of those two types of animations with the default animation properties.
containerStyle style Yes The style applied to the container view around everything
debugTouchArea bool Yes false Set this to true to visually see the thumb touch rect in green.
disabled bool Yes false If true the user won't be able to move the slider
maximumTrackTintColor string Yes '#b3b3b3' The color used for the track to the right of the button
maximumValue number Yes 1 Initial maximum value of the slider
minimumTrackTintColor string Yes '#3f3f3f' The color used for the track to the left of the button
minimumValue number Yes 0 Initial minimum value of the slider
onSlidingComplete function Yes Callback called when the user finishes changing the value (e.g. when the slider is released)
onSlidingStart function Yes Callback called when the user starts changing the value (e.g. when the slider is pressed)
onValueChange function Yes Callback continuously called while the user is dragging the slider
renderAboveThumbComponent function Yes null Function which returns a custom Component of your liking to be rendered above the thumb and pass as props index of a thumb starting from 0 and its current value.
renderBelowThumbComponent function Yes null Function which returns a custom Component of your liking to be rendered below the thumb and pass as props index of a thumb starting from 0 and its current value.
renderThumbComponent function Yes null Function which returns a custom Component of your liking to be rendered within the thumb.
renderTrackMarkComponent function Yes null Function which returns a custom Component of your liking to be rendered on top of the slider truck at the values provided by trackMarks property. It accepts an index of a mark from trackMarks array the method is being executed for.
step number Yes 0 Step value of the slider. The value should be between 0 and maximumValue - minimumValue)
thumbImage source Yes Sets an image for the thumb.
thumbStyle style Yes The style applied to the thumb
thumbTintColor string Yes '#343434' The color used for the thumb
thumbTouchSize object Yes {width: 40, height: 40} The size of the touch area that allows moving the thumb. The touch area has the same center as the visible thumb. This allows to have a visually small thumb while still allowing the user to move it easily.
trackClickable bool Yes false If true the user will be able to click anywhere on the track to set the value to that position.
trackMarks Array Yes The value should be an array of numbers between minimumValue and maximumValue. In order to render a mark on top of the slider track at provided numbers renderTrackMarkComponent property should also be provided.
trackRightPadding number Yes The padding that extends the track after the maximumValue (if not specified it will use the width of the thumb component)
trackStyle style Yes The style applied to the track
minimumTrackStyle style Yes The style applied to the track left of the thumb
maximumTrackStyle style Yes The style applied to the track right of the thumb
value number or Array Yes 0 Initial value of the slider. The value should be a number or array of numbers between minimumValue and maximumValue, which default to 0 and 1 respectively. Default value is 0. This is not a controlled component, e.g. if you don't update the value, the component won't be reset to its inital value.

MIT Licensed

react-native-slider's People

Contributors

adam-risberg avatar alessiocancian avatar badrey avatar brunolemos avatar dependabot-preview[bot] avatar dependabot[bot] avatar geert-untire avatar ijzerenhein avatar jamesreggio avatar janmarsicek avatar jaygarcia avatar jeanregisser avatar joseortiz9 avatar kapv89 avatar kiwikilian avatar manask88 avatar miblanchard avatar msand avatar muneneevans avatar nekiro avatar pawelangelow avatar philflores avatar philippkrone avatar pilotocheg avatar robertmetcalfephorest avatar rreusser avatar sfreeman28 avatar somersets avatar venon-it avatar vitalij-lutsyk avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-native-slider's Issues

Touch area does not have same center as visible thumb

Please check out example #8 from the snack https://snack.expo.dev/@miblanchard/@miblanchard-react-native-slider

How to reproduce:

Click on the center of the thumb
Expected: Thumb stays at position because center of thumb matches center touch area
Actual: The thumb moves to the right

Notes:

If thumbStyle width equals thumbTouchSize width, everything is fine. But if they differ this behaviour can be seen.

Screen.Recording.2022-11-21.at.14.20.34.mov
Screen.Recording.2022-11-21.at.14.24.08.mov

Does not support a11y features

We can't seem to get this slider to work with a11y OS features. Specifically, it becomes unresponsive with any kind of screen reader enabled, and can't be tapped or moved, making it unusable. Is this a known issue? This affects iOS and Android.

Module parse failed: Unexpected token

I'm getting this error when trying to use the web version of this component. How can I resolve this issue? It works properly on mobile.

./node_modules/@miblanchard/react-native-slider/lib/index.js 53:22
Module parse failed: Unexpected token (53:22)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|     }
|     if (Array.isArray(values) && Array.isArray(newValues)) {
>         return values?.map((value, index) => {
|             let valueToSet = newValues[index];
|             if (value instanceof Animated.Value) {

Track marks are not rendered

For some reason the track marks are not rendered on the first render. My work around looks like this:

onLayout={() => setTimeout(() => setMarks(trackMarks), 1000)}

Add custom components to track

Hi, thanks for this awesome fork!
However, I was wondering how can I add a or any other component in track, and this component will be overlap when the slider pass through.

image

Something similar to this.
https://github.com/Roxyhuang/react-slide-captcha
image

Currently I am using renderTrackMarkComponent but I don't think it is a correct way to use it.
Any suggestion?

renderBelowThumbComponent available in master but not yet published to npm

Hey,

I found this library today and I'm really excited about it. Great work, thank you. I really appreciate the ability to customize the styles to match our designs so that I don't need to write the component myself to get the styles we need.

I noticed a renderBelowThumbComponent prop in the master branch that has not yet been published to npm. That would be really helpful. Are there plans for a new release soon?

Thanks.

Thumb style changes on press

I am using an iOS style thumb style, as in the examples. I have set shadowOffset: { width: 0, height: 2 } and it works, but as soon as I press the thumb, the shadow offset height is gone and the thumb looks like shadowOffset: { width: 0, height: 0 }.

On Android, elevation works as expected.

Add an option to skip componentDidUpdate

When the parent component of the slider is updated while the user is moving the slider knob, a subtle lag can appear, this can be worse if the onValueChange trigger a setState that re-renders the whole DOM.
This part of the code seems to be the cause, maybe we could add a boolean prop to tell if we should let this part trigger ? Or is there another solution ?

minimumTrackStyle and maximumTrackStyle

Thanks for your component is great.

I just miss being able to change the style of each track separately. For example maxiumTrack height and miniumTrack height separately.

If you can add minimumTrackStyle and maximumTrackStyle it would be great

Thanks

Two thumb slider track is not animated

When using two thumbs, with maximum and minimum track colors, the track's colors are not animated.

Code for the slider below. I'm updating the state as a result of onSlidingComplete firing, which is why the track color appears after the slider stops moving. It re-renders, which moves the color over.

                    <Slider
                      trackClickable={true}
                      animateTransitions={true}
                      value={[item.start[0], item.end[1]]}
                      minimumValue={0}
                      maximumValue={30}
                      trackMarks={[0, 10]}
                      step={1}
                      thumbTouchSize={{width: 30, height: 30}}
                      thumbTintColor="#FFFFFF"
                      thumbStyle={{
                        borderColor: Palette.gray,
                        borderWidth: 0.5,
                        shadowColor: '#000000',
                        shadowOffset: {
                          width: 0,
                          height: 2,
                        },
                        shadowRadius: 1,
                        shadowOpacity: 0.1,
                      }}
                      minimumTrackTintColor={Palette.s1}
                      maximumTrackTintColor="#CECECE"
                      trackStyle={{
                        height: 1,
                      }}
                      onSlidingComplete={value =>
                        changeRange(item.name, value[0], value[1])
                      }
                    />

two-thumb-slider-no-track-color.mov

Always grabbing left part of the slider, it can get stuck

If I have a range slider with both ends close to each other, it is always grabbing the left end of the silder.

So when I move both ends to the left, it is impossible to change it back, because the right end gets stuck behind the left end.

slider_issue

Unable to upgrade react-native and react to latest version

Hi.

I am unable to upgrade my packages to the latest version when using this library.

Could you please have a look at this.


npm update 
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR!   react@"^17.0.1" from the root project
npm ERR!   peer react@">=16.8.0" from @miblanchard/[email protected]
npm ERR!   node_modules/@miblanchard/react-native-slider
npm ERR!     @miblanchard/react-native-slider@"^1.5.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"17.0.1" from [email protected]
npm ERR! node_modules/react-native
npm ERR!   react-native@"^0.64.0" from the root project
npm ERR!   peer react-native@">=0.59.0" from @miblanchard/[email protected]
npm ERR!   node_modules/@miblanchard/react-native-slider
npm ERR!     @miblanchard/react-native-slider@"^1.5.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\alen\AppData\Local\npm-cache\eresolve-report.txt for a full report.

There is some conflict between the packages, even thought in your page it says that i should not have problem upgrading react-native and react

Feature: please export SliderProps

I want to type my component but I am not able to since SliderProps are not exported. The community slider package does export it though (I migrated to yours which was definitely the best decision)

Bildschirmfoto 2022-04-25 um 10 17 19

Track Mark Rendered Incorrectly

Hi, it seems that when a track mark is rendered at the same value as the max value it will render at an incorrect position - to the left of the track end rather than at the end. See screenshot below where the track mark on the right should be rendering at the track end.

Screenshot 2022-05-06 at 10 29 42

Can be replicated by modifying the example snack listed in the README with the one below:

<SliderContainer caption="<Slider/> with track marks" sliderValue={[1]} trackMarks={[0, 7, 17]}> <Slider maximumValue={17} minimumValue={0} step={1} /> </SliderContainer>

Getting "Invariant Violation: inputRange must be monotonically non-decreasing" error

First of all, I'd like to thank you for providing this library - it has been extremely useful for my projects.
I've recently been seeing an error when trying to open a component using the Slider -
Invariant Violation: inputRange must be monotonically non-decreasing
This crashes the app on first use, but works on the subsequent launches.

Here's my environment info -

System:
    OS: macOS 10.15.7
    CPU: (12) x64 Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
    Memory: 856.17 MB / 16.00 GB
    Shell: 5.7.1 - /bin/zsh
  Binaries:
    Node: 15.12.0 - /usr/local/bin/node
    Yarn: 1.22.10 - /usr/local/bin/yarn
    npm: 7.6.3 - /usr/local/bin/npm
    Watchman: 4.9.0 - /usr/local/bin/watchman
  Managers:
    CocoaPods: 1.10.1 - /usr/local/bin/pod
  SDKs:
    iOS SDK:
      Platforms: iOS 14.4, DriverKit 20.2, macOS 11.1, tvOS 14.3, watchOS 7.2
    Android SDK:
      API Levels: 29, 30
      Build Tools: 28.0.3, 29.0.2, 30.0.3
      System Images: android-28 | Google Play Intel x86 Atom, android-30 | Google APIs Intel x86 Atom
      Android NDK: Not Found
  IDEs:
    Android Studio: 4.2 AI-202.7660.26.42.7351085
    Xcode: 12.4/12D4e - /usr/bin/xcodebuild
  Languages:
    Java: 1.8.0_271 - /usr/bin/javac
    Python: 2.7.16 - /usr/bin/python
  npmPackages:
    @react-native-community/cli: Not Found
    react: 16.13.1 => 16.13.1 
    react-native: 0.63.4 => 0.63.4 
    react-native-macos: Not Found
  npmGlobalPackages:
    *react-native*: Not Found

Slider hovers to the right side of my finger

Currently, the slider thumb hovers slightly to the right of the actual position of the user's finger on the screen. This behavior makes it so that sliders which touch the left side of a screen are impossible to set to their minimum value by manually sliding.

I tried to workaround this by mapping the value received by onValueChanged to the full range of the slider and setting the slider value to the new mapped value, which worked but lead to flickering since the slider is not a controlled component.

If the slider were a controlled component that would solve my issue, but if that is impossible, or if there is a reason that it shouldn't be controlled, would there be a way to interpolate my finger drag to a wider range? It would be similar to adjusting scrub speed on a video player seekbar.

Why does onValueChange return an array?

Here's an example of my implementation:

<Slider
    value={2}
    step={1}
    maximumValue={4}
    onValueChange={value => {
        // why is this an array?
        value = Array.isArray(value) ? value[0] : value;
        setValue(value);
    }}
    thumbTintColor={secondaryTextGray}
    minimumTrackTintColor={secondaryTextGray}
    maximumTrackTintColor={dividerBorderGray}
/>

Inaccurate _thumbHitTest for vertical sliders

I didn't have time to investigate further (I switched to a different package), but there's something wrong with _thumbHitTest on vertical sliders. Here's a video:

Screen.Recording.2022-10-23.at.10.18.07.AM.mp4

In this video, debugTouchArea was set to true and trackClickable was set to false.

(If you're on Firefox, the browser will complain that the video is corrupt for some reason. it's not; use a different browser).

Position does not match in a specific case

image

This happens when i have an action to reset the value without touching the slider, but disappears when the screen re-render for one more time.

Please help me find a way to resolve it. Thank you

Slider types

Please export types such as:

  • SliderProps
  • SliderOnChangeCallback

I'm unable to use these types to define my own component basing on this one.

Edit:
Found out SliderProps is possible to import from
@miblanchard/react-native-slider/lib/types

SliderOnChangeCallback is not exported from anywhere though.

Bug : Can't select 0 value of the slider

I have a problem when i try to select the Value 0 of the slider. I've set a default value of value = 5 , min = 0 and max =10 . When i try to select the value 0 the slider goes back to the middle but if i changed the minimumValue for example to min = 1 it works . My code is :

<Slider containerStyle={styles.slider} renderThumbComponent={() => ( <Image width={24} height={24} style={{ width: 24, height: 24 }} source={THUMB_IMG} /> )} minimumValue={min} maximumValue={max} value={value} step={1} onValueChange={([v]) => { onChange(v); }} trackStyle={{ height: 8, borderRadius: 30 }} minimumTrackTintColor={globalStyles.colors.bleu800} maximumTrackTintColor={globalStyles.colors.bleu800} />

Bug: Does not work vertically

I need a vertical slider, but when I set the containerStyle prop with:

{
    transform: [{rotate: '-90deg'}],
}

The slider is displayed correctly but it does not react as expected to touch events. I can tap on the track and the thumb moves more or less to the correct position, but it doesn't otherwise follow the movement of the finger.

The debugTouchArea seems to be correct tho.
image image

Screen.Recording.2021-06-22.at.15.44.49.mov

Restrict to "go back"

Is there a way to not let the user bring the slider back? for example, set it on 30 from 100, and not let the user go behind 30.

How would you make a cache bar?

I'm using the library as a slide of a custom video component, but I need to implement cache loading, something like:
image

cacheValue={playableDuration}
cacheTrackTintColor={'#fffff'}

PS: Sorry my english I'm not native.

inputRange exception if minimumValue is greater than maximumValue

I recently ran into a bug in my app which in some scenarios caused it to set the minimumValue prop to be greater than the maximumValue prop. This in turn caused the slider to throw a Invariant Violation: inputRange must be monotonically non-decreasing exception.

Perhaps it's not really an issue since the props are not supposed to be set like that, but I thought someone might find the information useful. Thanks for writing this great library! :)

Scrollock

Hi, when I tried your expo snack on my iPhone, I realized that there is no vertical scroll lock, as long you're sliding. Is there a way to prevent scrolling while sliding (without getting the ScrollViews ref and manipulation scrollEnabled true/false)

Vertical Slider Documentation + Bug

Hello,

I know the vertical slider functionality was only added recently but it would be good if this parameter could be added to the parameter list in the documentation.

Also, not sure if it was caused by the vertical slider functionality, but when activated, height and width style props are back to front. i.e. the height controls the width and the width controls the height.

Thanks for a fantastic package.

Update package

Hello i'm new here,

Just a question, when will you update the npm/yarn package (for minimumTrackStyle and maximumTrackStyle ) ? Or do I have a way to work with this project as react native package ?

Can't add pointerEvents="none" to renderAboveThumbComponent

First off, funny that you are also a codesmith guy. I was cohort 12. Nice work on this component! Using it for our video player at Openpath and the renderAboveThumbComponent prop is super useful. Only issue is that I am unable to add pointerEvents="none", as the wrapper needs to have that prop in order to allow touch events to flow through. I have a fullscreen button that is covered by the component and I am unable to press it when the thumb is below it. Normally I would just hide the component conditionally on seek, but in this case I can't and just adjust the opacity accordingly. Not sure the best solution to this, but simply another prop called something like renderAboveThumbComponentHasTouchEvents which defaults to true would do the trick.

Failing to install miblanchard/react-native-slider@latest

NPM fails to install the latest version of this package (2.0.0) because of a failing postinstall script.

npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! @miblanchard/[email protected] postinstall: `patch-package`
npm ERR! spawn ENOENT
npm ERR! 
npm ERR! Failed at the @miblanchard/[email protected] postinstall script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Cannot slide, but only click.

I cannot smoothly slide the slider, but only click on the track to move the thumb. Is that expected behavious?

 <Slider
        thumbTouchSize={{ width: 50, height: 50 }}
        containerStyle={[styles.sliderContainer, elevation]}
        style={styles.slider}
        trackStyle={{marginLeft: 10}}
        minimumValue={30}
        maximumValue={100}
        minimumTrackTintColor={colors.highlight}
        maximumTrackTintColor={colors.otherElements}
        onValueChange={value => dispatch(setRadius(value))}
        step={10}
        value={radius} />

Error: You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file.

When trying to implement your component, I get this error:

./node_modules/@miblanchard/react-native-slider/lib/index.js 53:22
Module parse failed: Unexpected token (53:22)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| }
| if (Array.isArray(values) && Array.isArray(newValues)) {

    return values?.map((value, index) => {

| let valueToSet = newValues[index];
| if (value instanceof Animated.Value) {

I used the same implementation as shown in example.

renderAboveThumbComponent index is not updating

Hi there,

I'm using the slider as such

      
    <SliderContainer sliderValue={value} trackMarks={trackMarks}>
<Slider
        minimumValue={minimumValue}
        maximumValue={maximumValue}
        step={step}
        renderAboveThumbComponent={(index) => {
          console.log('Here 1: ' + index);
          if (!renderAboveThumbComponent || !renderAboveThumbComponent(index))
            return undefined;
          const iconName = renderAboveThumbComponent(index);

          return (
            <Box left={-16}>
              {/*@ts-ignore*/}
              <Icon name={iconName} fontSize={50} />
            </Box>
          );
        }}
      />
</SliderContainer>

But the index does not update when I move the slider thumb.
Log always prints

Here 1: 0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.