Reputation: 17
I want to create a slider in react js but don't know how to implement this without using any third-party plugins.
Something similar to this https://mui.com/components/slider/
Upvotes: 0
Views: 706
Reputation: 341
You can try Something like this:
class Slider extends React.Component {
constructor() {
super();
this.state = { value: 0 };
this.changeValue = this.changeValue.bind(this);
}
changeValue() {
this.setState({ value: this.refs.input.value * this.props.max });
}
render() {
const sliderStyle = {
position: "relative",
width: "284px",
height: "28px"
};
const rangeStyle = {
webkitAppearance: "none",
appearance: "none",
touchAction: "pan-y",
position: "absolute",
margin: "0",
padding: "0",
width: "284px",
backgroundColor: "transparent"
};
const progressBarStyle = {
webkitAppearance: "none",
appearance: "none",
position: "absolute",
display: "block",
margin: "0",
top: "13px",
left: "13px",
width: "256px",
height: "3px",
zIndex: "-1",
backgroundColor: "#D7D7D7"
};
return (
<div
style={sliderStyle}
aria-valuemin={this.props.min}
aria-valuemax={this.props.max}
aria-valuenow={this.state.value}
aria-valuetext={this.state.value}
>
<input
ref="input"
type="range"
onChange={this.changeValue}
defaultValue={this.props.min}
min={this.props.min}
max={this.props.max}
step={this.props.max / 100}
style={rangeStyle}
/>
<progress
value={this.state.value}
min={this.props.min}
max={this.props.max}
style={progressBarStyle}
></progress>
</div>
);
}
}
ReactDOM.render(<Slider min={0} max={1} />, document.querySelector("#root"));
:root {
--thumb-shadow:
0 3px 8px rgba(0, 0, 0, .15),
0 1px 1px rgba(0, 0, 0, .16),
0 3px 1px rgba(0, 0, 0, .10)
}
body {
margin: 0;
width: 100vw;
height: 100vh;
display: -webkit-flex;
display: flex;
justify-content: center;
align-items: center;
background-color: #EFEFF4
}
* { outline: none }
progress::-webkit-progress-value { background-color: #007AFF }
progress::-webkit-progress-bar {
background-color: #B6B6B6;
border-radius: 1.5px;
overflow: hidden
}
input::-webkit-slider-thumb {
-webkit-appearance: none;
appearance: none;
height: 28px;
width: 28px;
border: none;
border-radius: 50%;
background-color: white;
z-index: 2;
box-shadow: var(--thumb-shadow)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id=root>
</div>
Upvotes: 1