Erik Kubica
Erik Kubica

Reputation: 1230

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

Upvotes: 6

Views: 9904

Answers (2)

DeepShr
DeepShr

Reputation: 11

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.

Upvotes: 1

Daltron
Daltron

Reputation: 1856

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.

Upvotes: 24

Related Questions