Open In App

How to add Input Slider in React JS ?

We will learn how to add an input slider in React JS. React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It was introduced by Facebook and a community of individual developers and companies.

Prerequisites:

Approach:

To add our slider input we are going to use the react-input-slider package. The react-input-slider package helps us to integrate the slider input into our app. So first, we will install the react-input-slider package and then add a slider input on our homepage.



Steps to Create React Application And Installing Module:

Step 1: Create a React application using the following command

npx create-react-app gfg

Step 2: After creating your project folder i.e. example, move to it using the following command



cd gfg

Step 3: Install the required package

npm i react-input-slider

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-input-slider": "^6.0.1",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4",
}

Example: Adding the slider input after installing the package we can easily add a slider input on any page in our app.




import React, { useState } from 'react';
import Slider from 'react-input-slider';
 
export default function GfgInput() {
    const [state, setState] =
        useState({ x: 15, y: 15 });
    return (
        <div>
            <h2>
                GeeksforGeeks ReactJs - Slider Input
            </h2>
            <div>
                ({state.x}, {state.y})
                <Slider axis="xy" x={state.x}
                    y={state.y} onChange={setState} />
                <Slider
                    axis="x"
                    x={state.x}
                    onChange={
                        ({ x }) =>
                            setState(state => ({ ...state, x }))}/>
                <Slider axis="y" y={state.y} onChange=
                    {
                        ({ y }) =>
                            setState(state => ({ ...state, y }))
                    } />
            </div>
        </div>
    );
}

Steps to Run the Application: Run the below command in the terminal to run the app.

npm start

Output: We are importing the Slider component and useState hook from react. Then we are using the useState hook to store the value of the input. After that, we are adding our slider input using the installed package.


Article Tags :