Uncontrolled Range Input

ReactReactBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to create an uncontrolled range input element in React that allows users to select values from a range of numbers by sliding a button along a horizontal line. We will use a callback function to pass the selected value to the parent component. By the end of this lab, you will have a better understanding of how to use the onChange event and defaultValue property in React.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL react(("`React`")) -.-> react/FundamentalsGroup(["`Fundamentals`"]) react/FundamentalsGroup -.-> react/jsx("`JSX`") react/FundamentalsGroup -.-> react/event_handling("`Handling Events`") subgraph Lab Skills react/jsx -.-> lab-38361{{"`Uncontrolled Range Input`"}} react/event_handling -.-> lab-38361{{"`Uncontrolled Range Input`"}} end

Uncontrolled Range Input

index.html and script.js have already been provided in the VM. In general, you only need to add code to script.js and style.css.

To create a slider in React, use the Slider component and pass in the min, max, defaultValue, and onValueChange props.

In the Slider component, set the type of the <input> element to "range" to create a slider. Use the defaultValue prop passed down from the parent as the uncontrolled input field's initial value. Use the onChange event to fire the onValueChange callback and send the new value to the parent.

Here's the code for the Slider component:

const Slider = ({
  min = 0,
  max = 100,
  defaultValue,
  onValueChange,
  ...rest
}) => {
  return (
    <input
      type="range"
      min={min}
      max={max}
      defaultValue={defaultValue}
      onChange={({ target: { value } }) => onValueChange(value)}
      {...rest}
    />
  );
};

To render the Slider component, use ReactDOM.createRoot and pass in the onValueChange callback function:

ReactDOM.createRoot(document.getElementById("root")).render(
  <Slider onValueChange={(val) => console.log(val)} />
);

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Uncontrolled Range Input lab. You can practice more labs in LabEx to improve your skills.

Other React Tutorials you may like