Range Slider using Material UI in React
Range Slider using Material UI in React involves the use of a slider component. This component is used to handle the range input in the react material UI components.
Prerequisites
Approach
To create a Range Slider using material UI in react that takes the range input we will first install and import the MUI slider component. Pass the custom-defined range for the range input to the slider component and a useState variable to store the value on the input.
Steps to create React Application
Step 1: Initialize the react project using this command in the terminal
npx create-react-app myapp
Step 2: Move to the project directory
cd myapp
Step 3: Install Material UI library
npm i @material-ui/core
Project Structure:
The updated dependencies in package.json file will look like
{
"dependencies": {
"@material-ui/core": "^4.12.4",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}
}
Example: Range slider for Current Temperature using Material UI with few mentioned range points.
Javascript
// Filename - App.js //We use useState for the initial set values import React, { useState } from "react" ; import "./App.css" ; //we import slider from material ui import { Slider } from "@material-ui/core" ; function App() { //Providing different values with labels const gfg = [ { value: 0, label: "0°C" , }, { value: 25, label: "25°C" , }, { value: 50, label: "50°C" , }, { value: 100, label: "100°C" , }, ]; const [val, setVal] = useState([0, 40]); const updateRange = (e, data) => { setVal(data); }; return ( <div className= "App" > <h1> What is the current temperature in your City ? </h1> <div style={{ width: 500, margin: 60 }}> <span> Temperature : </span> <Slider value={val} onChange={updateRange} marks={gfg} /> </div> </div> ); } export default App; |
CSS
/* Filename - App.css*/ body { margin : 0px ; } .App { font-family : sans-serif ; color : green ; font-size : 16px ; } span { color : red ; font-size : 18px ; font-weight : 13px ; font-family : Verdana , Geneva, Tahoma , sans-serif ; } |
Steps to run the application: Use this command in the terminal inside project directory.
npm start
Output: This output of Range Slider will be visible on the http://localhost:3000/ on the browser window.
Contact Us