I have the below component that works fine with this.refs.searchString.value
but would it work if I just event.target.value
instead? If so, which one is preferred method? What's the pros and cons of each?
const SearchBar = React.createClass({
handleSubmit (event) {
event.preventDefault()
const formattedSearchString = this.refs.searchString.value.replace(/[^a-z]/gi, "").toLowerCase()
this.refs.searchString.value = ''
this.props.submitSearch(formattedSearchString)
},
render() {
return (
<form className="form form-group has-info col-md-4 text-align-center" onSubmit={this.handleSubmit}>
<input className="search-input form-control" type="text" ref="searchString" placeholder=" . . . enter pokemon name" />
<button className="btn btn-info btn-raised" type="submit" name="button">Search!</button>
</form>
)
}
})
As mentioned in the documentation, we shouldn't overuse refs, the preferred method is to use event.target.value
using Controlled Components.
const SearchBar = React.createClass({
getInitialState(){
return {textValue: ""};
},
onTextChange(evt) {
this.setState({textValue: evt.target.value});
},
handleSubmit (event) {
event.preventDefault()
const formattedSearchString = this.state.textValue.replace(/[^a-z]/gi, "").toLowerCase()
this.refs.searchString.value = ''
this.props.submitSearch(formattedSearchString)
},
render() {
return (
<form className="form form-group has-info col-md-4 text-align-center" onSubmit={this.handleSubmit}>
<input className="search-input form-control" type="text" value={this.state.textValue} onChange={this.onTextChange} placeholder=" . . . enter pokemon name" />
<button className="btn btn-info btn-raised" type="submit" name="button">Search!</button>
</form>
)
}
})
If you use event.target.value
, you have to keep track of state of form inputs with useState
. Everytime state changes, that means after each keystroke, it will rerender the app which is very expensive operation.
Using useRef
will preserve state without rerendering.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With