Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RealDeanZhao/ea0a7f6846dfc48236bd94bb75d775b1 to your computer and use it in GitHub Desktop.
Save RealDeanZhao/ea0a7f6846dfc48236bd94bb75d775b1 to your computer and use it in GitHub Desktop.
redux form unfocus when input the first charactor
// https://github.com/erikras/redux-form/releases/tag/v6.0.0-alpha.14
Let's look at what that means:
WRONG: :cry: :-1:
class MyForm extends Component {
render() {
const { handleSubmit } = this.props
return (
<form onSubmit={handleSubmit}>
<Field name="username" component={props => // <----- CANNOT DO THIS
<div>
<input type="text" {...props}/>
{props.touched && props.error && <span>{props.error}</span>}
</div>
}/>
</form>
)
}
}
RIGHT: :smile: :+1:
// define "fat arrow component" outside of render()
const renderInput = props =>
<div>
<input type="text" {...props}/>
{props.touched && props.error && <span>{props.error}</span>}
</div>
class MyForm extends Component {
render() {
const { handleSubmit } = this.props
return (
<form onSubmit={handleSubmit}>
<Field name="username" component={renderInput}/> // <-- refer to component
</form>
)
}
}
That sucks! Why?
The reason is that defining a fat arrow component inside render creates a new component on every form render, which causes each Field to rerender (because the component prop is !==). If you don't care that much about performance, and you are using a custom input widget, you might still be able to get away with it, but if you are using an <input> component, that input will lose its focus whenever the form is rerendered.
It's not that bad. Take a look at the Examples and see if you don't agree that the code is cleaner this way.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment