Reputation: 57
I am new-ish to React and trying mimic a more complicated version of the following scenario:
In my real example that I am mimicking here, in step 2, lots of things change in response to the updating of the state value, not just a direct update of the value. I want to provide a "reset" in my parent, that in turn should be reflected in this one child component that has a range slider.
Here is my simple example:
import React, { useState } from "react";
export const App = () => {
const [rangeValue, setRangeValue] = useState(0)
const reset = (e) => {
e.preventDefault()
setRangeValue(0)//reset state to 0 in App
//how can I get the initial Position in Range component back to 0?
}
return (
<div>
<p>The range value is: {rangeValue}</p>
<Range setRangeValue = {setRangeValue}/>
<p><a href="/#" onClick={reset}>reset</a></p>
</div>
)
}
const Range = ({setRangeValue: setRangeValue}) =>
{
const handleChange = (event) => {
setRangeValue(event.target.value)
}
return (
<input
type="range"
min="0"
max="10"
step="1"
defaultValue={0}
onChange={(event) => {handleChange(event)}} />
)
}
export default App;
Here is a code sandbox: https://codesandbox.io/s/github/FergusDevelopmentLLC/range-test
What is the proper way to accomplish such an idea?
Upvotes: 1
Views: 2867
Reputation: 2206
You would want to make your Range component controlled by passing the value to it from the parent and getting rid of the default
import React, { useState } from "react";
export const App = () => {
const [rangeValue, setRangeValue] = useState(0)
const reset = (e) => {
e.preventDefault()
setRangeValue(0)//reset state to 0 in App
//how can I get the initial Position in Range component back to 0?
}
return (
<div>
<p>The range value is: {rangeValue}</p>
{/* pass the value here */}
<Range rangeValue={rangeValue} setRangeValue = {setRangeValue}/>
<p><a href="/#" onClick={reset}>reset</a></p>
</div>
)
}
const Range = ({rangeValue, setRangeValue: setRangeValue}) =>
{
const handleChange = (event) => {
setRangeValue(event.target.value)
}
return (
<input
type="range"
min="0"
max="10"
step="1"
value={rangeValue} // <-- here get the value from parent, when reset it will come down from parent again without whatever value it was reset to
onChange={(event) => {handleChange(event)}} />
)
}
export default App;
Upvotes: 2