hamidkardorost hamidkardorost - 1 year ago 169
React JSX Question

React input defaultValue doesn't update with props changes

i have an app by : react & redux & react-router

when the url changes , the props changes depends on the url ":personId" param

mapStateToProps = (state,router)=>({
onePerson : state.persons.filter((person,i)=>person.id===router.params.personId)[0]

and also i have an input which want to be linked to props and automatic update by new props

<input type="text" defaultValue={this.props.onePerson.name}/>

as the url changes and props changes accordingly ... defaultValue not changes and remains the same as it is

how can i overcome this issue?

note that i don't want to use "controlled input"

Answer Source

That's because the defaultValue is only used the first time the component gets rendered. If you need to update the value later, you have to use a controlled input.


From the React Docs:

The defaultValue and defaultChecked props are only used during initial render. If you need to update the value in a subsequent render, you will need to use a controlled component.

I guess you could remove and re-add the component to give it a new defaultValue, but you really shouldn't.