Range Slider
Develop a range slider component for selecting a value within a specified range.
Solution
Selected value: 5
Explanation
Range Slider and State Management
The user can select a value from 0 to 10 using a range slider in this example. The current value of the slider is stored in the state using the useState
hook. The default value is set to 5 to be precise, but the inbuilt default will be the middle of the range.
When the user interacts with the slider, the handleChange
function is triggered. The slider's value is obtained from the event and is converted to an integer using parseInt
. The state is then updated to reflect the selected value.
Displaying the Selected Value
The selected value is displayed dynamically in a p
tag and controlled through the value state
.
Range Slider Configuration
The range input field is configured with a minimum value of 0 and a maximum value of 10. The step
property is set to 1, meaning users can only select whole numbers.
The datalist
element is used to create ticks and is valid across browsers. Unfortunately, labels are not widely available.
Handling Edge Cases
To handle any potential edge cases, the handleChange
function includes a fallback value of 5 (the midpoint of the range) in case the input is invalid or cannot be parsed into an integer. This ensures that the slider will always have a valid value.
Code
import { useState } from "react";
import styles from "./Solution.module.css";
const Solution = () => {
const [value, setValue] = useState(5);
const handleChange = (output: string) => {
const eventValue = parseInt(output) ?? 5;
setValue(eventValue);
};
return (
<>
<label className={styles.label} htmlFor="js-id">
Rate your confidence with React from 0 - 10
</label>
<p>
Selected value: <span className={styles.value}>{value}</span>
</p>
<input
type="range"
onChange={(event) => handleChange(event?.target?.value)}
className={styles.input}
min={0}
max={10}
step={1}
list="markers"
name="js-value"
id="js-id"
/>
<datalist id="markers">
<option value="0"></option>
<option value="1"></option>
<option value="2"></option>
<option value="3"></option>
<option value="4"></option>
<option value="5"></option>
<option value="6"></option>
<option value="7"></option>
<option value="8"></option>
<option value="9"></option>
<option value="10"></option>
</datalist>
</>
);
};
export default Solution;
Styling
.label {
display: block;
font-weight: bold;
margin-bottom: 10px;
}
.input {
width: 400px;
cursor: pointer;
height: 10px;
}
.value {
font-weight: bold;
color: var(--font-color-accent);
}