Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react ref.example.value vs. e.target.value

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>
    )
  }
})
like image 943
stackjlei Avatar asked Oct 28 '16 09:10

stackjlei


2 Answers

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>
    )
  }
})
like image 128
Niyoko Avatar answered Oct 16 '22 08:10

Niyoko


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.

like image 2
Yilmaz Avatar answered Oct 16 '22 08:10

Yilmaz