Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the DOM not updating with state change in ReactJS?

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;
like image 699
Rajan Karmaker Avatar asked Aug 28 '19 09:08

Rajan Karmaker


3 Answers

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")

like image 70
Dacre Denny Avatar answered Oct 02 '22 04:10

Dacre Denny


You miss the unit here,

<label style={ { fontSize: `${slider}px` } }>Example range</label>

Demo

like image 43
ravibagul91 Avatar answered Oct 02 '22 04:10

ravibagul91


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

like image 40
Jayraj Avatar answered Oct 02 '22 03:10

Jayraj