Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reactjs - Input defaultValue is set but not showing

Noticed some weirdness that defaultValue is set for input, but sometimes it's not visible when page is refreshed. I have tried console.log then component re-renders multiple times as data is loaded, on the last re-render the component contains the required value, as you can see on screenshot, but it's not shown. Any idea why? Thank you

<input type="text" name={this.props.question.id}
                defaultValue={defaultValue}
                onChange={this.onSingleChange.bind({
                    selectAnswer: this.props.selectAnswer,
                    question: this.props.question,
                    form: this.props.fid
                })}
                className="form-control"
            />

enter image description here

like image 802
Erik Kubica Avatar asked Aug 24 '26 17:08

Erik Kubica


2 Answers

I had this same issue before. My solution was to add a key prop to my input that was a random number.

key={`${Math.floor((Math.random() * 1000))}-min`}

From what I have read, this has to do with defaultValue being set only on the initial render. The random number causes a re-render with the right default value.

Hope that helps.

like image 120
Daltron Avatar answered Aug 26 '26 09:08

Daltron


I agreed with the solution provided by @Daltron, but it can also be solved by putting the key prop binding with its value instead of adding random values.

like image 24
DeepShr Avatar answered Aug 26 '26 08:08

DeepShr



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!