How to create horizontal scrollbar with views in React native

Introduction :

This is an example program to show you how we can create one horizontal scrollbar in React native. React native ScrollView component comes with a property to make one ScrollView horizontal. This prop is horizontal By default, it’s value is false i.e. by default, we got one vertical ScrollView. We can convert it to a horizontal ScrollView by marking it false.

Example program :

In this example react native program, we are working on a page called HomeScreen. Below is the complete code :

import React from 'react';
import {View, ScrollView} from 'react-native';

const SquareView = (props) => {
  return (
    <View
      style={{
        height: props.size,
        width: props.size,
        backgroundColor: props.color,
      }}
    />
  );
};

export default function HomeScreen() {
  return (
    <ScrollView horizontal={true} >
      <SquareView size={100} color="red" />
      <SquareView size={100} color="blue" />
      <SquareView size={100} color="green" />
      <SquareView size={100} color="yellow" />
      <SquareView size={100} color="gray" />
      <SquareView size={100} color="cyan" />
      <SquareView size={100} color="black" />
    </ScrollView>
  );
}

Here, SquareView is a square component that takes the size and color in props. We have seven SquareView components inside a ScrollView. horizontal prop is true for the ScrollView. It will create one horizontal scrollable view with all the views inside as like below :

React native horizontal scrollview

1. alwaysBounceHorizontal :

It takes one boolean value and works only on iOS. By default, it’s value is false. If we mark it true, the scroll bar will bounch if it reaches to the end even if the content is smaller than the scroll view itself.

2. showsHorizontalScrollIndicator :

It is used to show one horizontal scroll indicator. It is a boolean value and by default it is true.

3. scrollTo :

This method is defined as below :

scrollTo(
  options?: {x?: number, y?: number, animated?: boolean} | number,
);

This is used to scroll to a specific position using animation or without animation.

4. scrollToEnd :

This is used to scroll one scrollbar to the end. For horizontal scrollbar, it scrolls to the right. It is defined as below :

scrollToEnd(([options]: { animated: boolean, duration: number }));

We can also animate the scrolling using animate prop.

Where is the color and why codevscolor ?

Long story short, I love paintings and I paint on weekends. We(me and my wife) have one Youtube channel. Below is a video that I did recently. If you love this please do subscribe to support us 😊