Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Material UI TextField value is not updating

There are four files: createPollForm.js, formOptions.js, optionList.js, and option.js

createPollForm has a state of option array with initial value:

const [options, setOptions] = useState([{
        id: uuidv4(),
        value: ""
    }]);

const handleOptionsChange = value => {
       setOptions(value);
}

return(
        <FormOptions 
               options={options}
               handleOptionsChange={handleOptionsChange}
        />
)

formOptions.js receives handleOptionsChange from createPollForm.js :

const handleValue = id => {
      const result = options.filter(option => option.id === id)
      return result[0].value
}

const handleChangeValue = (e, id) => {
      options.forEach(option => {
          if(option.id === id){
              option.value = e.target.value
          }
      })

      handleOptionsChange(options)
}

return (
     <OptionList 
            options={options}
            handleValue={handleValue}
            handleChangeValue={handleChangeValue}
     />
)

optionList.js contains all the option TextFields

return (
        <div>
            {options.map(option => (
                <Option 
                    key={option.id} 
                    id={option.id}
                    handleValue={handleValue}
                    handleChangeValue={handleChangeValue}
                />
            ))}
        </div>
    )

option.js:

return(
       <TextField 
           label="Option"
           value={props.handleValue(props.id)}
           onChange={e => props.handleChangeValue(e, props.id)}
       />
    )

Before adding the value in TextField in option.js, everything works fine, however, after adding the value with the handleValue function for assigning value to each option TextField, the TextField will just remain blank when I am typing in the corresponding TextField even though I can see the value of option array state is updated through console.log. Therefore, I assume for some reason the TextField has trouble to read the most updated value from option array.

Could anyone help me with this? I just started learning reactjs, any help would be greatly appreciated.

like image 509
user10491490 Avatar asked Nov 24 '25 10:11

user10491490


1 Answers

In handleOptionsChange method in createPollForm.js. update state like given:

setOptions({...options,value})

because initial value is object, and you passing value.

like image 117
pl2ern4 Avatar answered Nov 26 '25 22:11

pl2ern4



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!