I want to update the font size of an element using a slider. When I slide the slider, the value changes and I can successfully store that into my state using e.target.value
.
But the problem is the font size does not update as I expect. I can't figure out why?
Here is my React component code:
import React, { useState } from 'react';
function App() {
const [slider, setSlider] = useState(20);
const handleChange = (e) => {
setSlider( e.target.value );
console.log(slider);
}
return (
<div className="container">
<label style={ { fontSize: slider } }>Example range</label>
<input
type="range"
className="custom-range"
id="customRange1"
min="10"
max="30"
defaultValue={slider}
onChange={handleChange}
/>
</div>
);
}
export default App;
If you replace defaultValue
with the value
prop, and update your <label>
elements style
as shown below, then your component will work as expected:
function App() {
const [slider, setSlider] = useState(20);
const handleChange = (e) => {
setSlider( e.target.value );
console.log(slider);
}
return (<div className="container">
{/* Format valid value for fontSize property */ }
<label style={{ fontSize: `${slider}px` }}>Example range</label>
{/* Supply slider state via value prop rather than defaultValue */ }
<input
type="range"
className="custom-range"
id="customRange1"
min="10"
max="30"
value={slider}
onChange={handleChange}
/>
</div>
);
}
See this link for relevant documentation discussing form/inputs elements that have a value
prop specified (referred to as "Controlled components")
You miss the unit here,
<label style={ { fontSize: `${slider}px` } }>Example range</label>
Demo
const [slider, setSlider] = useState(20);
Here, you are assigning Number to slider and then updating it with string (console.log(typeof e.target.value))
i.e. you are changing data type of something, which is not good practice to code. Because it may affect your code, if you are dependent on it(slider) at more than one places, your program may break and you would never find such mistakes, follow good coding practices.
Try using setSlider(Number(e.target.value));
instead of setSlider(e.target.value);
https://codesandbox.io/s/pedantic-black-x6uzx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With