Utilize a slider component to navigate a horizontal scrollView within a React Native application

I'm in the process of setting up a slider within a horizontal ScrollView to enhance page scrolling speed. I've successfully linked the page position to the slider value, so as I scroll the page, the slider thumb moves correspondingly.

My setup involves using React Native Slider and a ScrollView. Take a look at the current result:

https://web.archive.org/web/20190624092331/https://www.bonellicio.us/work/img.gif

Being new to RN, it's likely that I'm overlooking something crucial here.

class Comp extends Component {

  state = {
    width : 0, 
    value : 0, 
    cursor : 0
  }

  moveTheCursor = (val) => {
    this.scrollView.scrollTo({x: val, y: 0, animated: true})
  }

  scrollTheView = (event) => {
    this.setState({
      value : Math.floor(event.nativeEvent.contentOffset.x),
      cursor : Math.floor(event.nativeEvent.contentOffset.x)
    })
  }

  checkWidth = ({nativeEvent}) => {
    arrayWidth.push(nativeEvent.layout.width)
    let ww = (arrayWidth[0] * this.props.data.length) - Math.round(Dimensions.get('window').width);
    this.setState({
      width : ww,
    })
  }

  render() {
    return (
      <React.Fragment>
        <ScrollView 
          ref={ref => this.scrollView = ref}
          horizontal
          style={styles.car}
          scrollEventThrottle={1}
          onScroll={this.scrollTheView}
          showsHorizontalScrollIndicator={false}
          decelerationRate={0}
          //snapToInterval={200} //your element width
          snapToAlignment={"center"}
        >

        </ScrollView>
          
        <Slider
          style={styles.containerSlide}
          thumbImage={require("./../../assets/img/buttons/thumb.png")}
          trackImage={require("./../../assets/img/buttons/bar.png")}
          minimumValue={0}
          maximumValue={this.state.width}
          onValueChange={this.moveTheCursor}
          value={this.state.cursor}
        />
        

      </React.Fragment>
    );
  }
} 

The issue arises when I attempt to use the slider thumb to scroll the page, as it triggers a scroll that resets the thumb position, leading to inaccurate behavior (flickering predominantly). Is there a solution to break out of this cycle?

Answer №1

To achieve the desired functionality, you can utilize a combination of Slider's onSlidingStart and onSlidingComplete events along with ScrollView's scrollEnabled property.

Here is an example implementation:


const [isSliding, setIsSliding] = useState(false);

<ScrollView scrollEnabled={!isSliding}>
   <Slider 
      onSlidingStart={() => setIsSliding(true)}
      onSlidingComplete={() => setIsSliding(false)}
   />
</ScrollView>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to make a model draggable but disable it specifically on input fields?

I'm exploring the implementation of a draggable feature by using both a JavaScript directive and the simple draggable="true" attribute. (Testing each method separately). Here's my basic code structure: <div draggable="true& ...

I keep getting redirected to a blank page by JS

I've created a JavaScript script that smoothly fades in the page when a user enters it and fades out when they click a link to another page. The script is working as intended, but I'm facing an issue with anchor links on the page. Whenever I clic ...

You are unable to use multiple background colors on a material UI snackbar

Is there a way to apply multiple background colors to a material UI snackbar? I attempted using linear-gradient as shown below, but it didn't work. import Snackbar from 'material-ui/Snackbar'; const bodyStyle = { border: `2px solid ${co ...

Is there a way to determine whether an object possesses a specific property or not?

Searching for a solution that works across various browsers to determine whether an object contains a specific property. For example, let's say we have a span element: var elem = document.getElementById('span1'); if(elem.hasOwnProperty(&a ...

Configuring Axios header in Java backend based on the value stored in the express session

I am currently working on a frontend app using node.js express for server-side rendering. This app calls java backend endpoints and I use Axios to make the requests. A specific header named "agent-id" needs to be set in every request that is sent from expr ...

JointJS: I need to extract the source value from the JSON text with the ID field

I need to extract the text value from "source":{"id": using JSON data in this specific JavaScript object : { "cells": [ { "type": "devs.Model", "size": { "width": 40, "height": 40 }, "inPorts": [""], "outPorts": ["" ...

Querying a map within a Mongo function results in an empty variable when accessed outside of the function, but

Currently, I am facing an issue while trying to create an array of objects using the map function in Mongo and node/express JS. Strangely, when I utilize console.log outside the map function, the array appears empty. However, within the map function, each ...

"Encountering a mysterious internal server error 500 in Express JS without any apparent issues in

My express.js routes keep giving me an internal server error 500, and I have tried to console log the variables but nothing is showing up. Here are the express routes: submitStar() { this.app.post("/submitstar", async (req, res) => { ...

Angular renders HTML elements

Greetings! I am currently experimenting with using AngularJS for the frontend and Wordpress as the backend of my project. To load content from Wordpress into Angular, I am utilizing a JSON wordpress plugin along with making $http requests. The content th ...

The Node.js execSync functionality is not functioning as expected, as the changes made to the system are not taking effect

I'm looking to prevent chrome.exe from accessing the internet through the Windows firewall. The specific command I need to use is netsh advfirewall firewall add rule name="Block Chrome" dir=out action=block program="C:\Program Files (x86)\G ...

Resolving a Routing Problem with moment.js

Hi everyone, I'm new to working with express.js and backend routing. I'm encountering an error with my server code and would appreciate any insights on what might be causing it. I've already tried using res.end() with plain text, but the err ...

Tally up the values of selected checkboxes

  I'm in search of a method to tally up data-values associated with checkboxes. In the example provided below, selecting locations from the checkboxes results in the calculation of primary values, which are displayed in the green box. I also need to ...

What is the best way to alter something based on the current date?

My goal is to dynamically change a message based on how close a specific date is. The objective is to update an element of a webpage to display "Renewal Unnecessary" when the date is more than 3 months away, "Renewal upcoming" when the date is less than 3 ...

Are there any modules in Angular 8 that are used across various projects?

I am facing a challenge with managing two projects that share the same core functionality. These projects have identical layouts and pages, but certain components and modules are specific to each project. Currently, I maintain two separate Angular projects ...

Applying CSS styles to a class dynamically using JavaScript

Is there a way to dynamically add a new CSS property to an existing class using JavaScript? Let's say I have a class called .test with some pre-defined styling. How can I append the property color: blue; to this class using JavaScript? const elm ...

Modify the background color when hovering using jquery

In order to have buttons with variable colors and a different hover color, I have to apply inline CSS. Since the hover color cannot be added using inline CSS, I need to use JavaScript. I attempted to achieve this using the .hover() function, but the colors ...

Modifying HTML input value dynamically using JavaScript does not trigger the onchange event

Within my HTML code, I have an input field that is included in a form. Here is the input field snippet: <input type="text" name="group[{$sConfigurator.groupID}]" value="{$optionTopOptionID}" id="{$formSelectID}" onChange="this.form.submit();"/> A j ...

Transferring checkbox data to Bootstrap modals and dynamically summoning specific div modals using their unique identifiers

I have been trying to populate the checkbox values into corresponding modal divs based on button clicks, but I am facing difficulties in achieving it. Desired outcome: The buttons should trigger the display of selected checkbox values in their respective ...

The anchor tag is failing to register when placed inside a dynamically created table cell

I'm attempting to place an anchor tag within a cell of an HTML table. Here is the code I am using, but for some reason, the tag is not being identified and no hyperlink is displayed in that cell. Is there an issue with the syntax? $("#tranTbodyI ...

What steps can be taken to prevent the Google search bar from adjusting focus in a Chrome extension?

Currently, I am in the process of developing a Chrome extension that incorporates some of the key functions from the vimperator plugin on Firefox. One issue I am facing is capturing keystrokes before a webpage does. An example of this difficulty can be se ...