I use the react-range package for personal purposes of my project, the problem is that I cannot save the value when the page is refreshed, I tried to use the local storage but I could not
As you understand, I need to save the value using local storage, in addition, I will leave a link to mine on codesandbox link
SideBarBlurChange.jsx
JavaScript
x
95
95
1
import React, {useEffect, useState} from "react";
2
import {getTrackBackground, Range} from "react-range";
3
4
const STEP = 0.1;
5
const MIN = 0;
6
const MAX = 100;
7
8
export default function SideBarBlurChange(props) {
9
10
const [values, SetValues] = useState([20])
11
12
const SaveChanges = () => {
13
alert(values)
14
}
15
16
return (
17
<>
18
<div
19
style={{
20
display: "flex",
21
justifyContent: "center",
22
flexWrap: "wrap",
23
}}
24
>
25
<Range
26
values={values}
27
step={STEP}
28
min={MIN}
29
max={MAX}
30
onChange={(values) => SetValues(values)}
31
renderTrack={({ props, children }) => (
32
<div
33
onMouseDown={props.onMouseDown}
34
onTouchStart={props.onTouchStart}
35
style={{
36
props.style,
37
height: "36px",
38
display: "flex",
39
width: "100%"
40
}}
41
>
42
<div
43
ref={props.ref}
44
style={{
45
height: "5px",
46
width: "100%",
47
borderRadius: "4px",
48
background: getTrackBackground({
49
values: values,
50
colors: ["#548BF4", "#ccc"],
51
min: MIN,
52
max: MAX
53
}),
54
alignSelf: "center"
55
}}
56
>
57
{children}
58
</div>
59
</div>
60
)}
61
renderThumb={({ props, isDragged }) => (
62
<div
63
{props}
64
style={{
65
props.style,
66
height: "42px",
67
width: "42px",
68
borderRadius: "4px",
69
backgroundColor: "#FFF",
70
display: "flex",
71
justifyContent: "center",
72
alignItems: "center",
73
boxShadow: "0px 2px 6px #AAA"
74
}}
75
>
76
<div
77
style={{
78
height: "16px",
79
width: "5px",
80
backgroundColor: isDragged ? "#548BF4" : "#CCC"
81
}}
82
/>
83
</div>
84
)}
85
/>
86
<output style={{ marginTop: "30px" }} id="output">
87
{values[0].toFixed(1)}
88
</output>
89
90
<button onClick={() => SaveChanges()}>Save</button>
91
</div>
92
</>
93
);
94
}
95
Advertisement
Answer
I think your main problem was that localStorage doesn’t store anything besides strings. You’re going to want to parseInt then check to make sure localStorage isn’t null. Can you try this and see if it works?
JavaScript
1
8
1
const ls = parseInt(window.localStorage.getItem('values'));
2
const [values, SetValues] = useState(ls ? [ls] : [20]);
3
4
const SaveChanges = () => {
5
alert(values);
6
localStorage.setItem('values', values);
7
}
8