0

I'm trying to understand why there are refs in React, and what problems they can help me to solve. In my opinion, React documentation is not great with explaining why i would need to use refs, and i could not find any good articles either. According to the documentation, there are a few good use cases for refs :

Managing focus, text selection, or media playback. Triggering imperative animations. Integrating with third-party DOM libraries.

However, i can't figure out any practical usage for it.

Also, this example is taken from css-tricks :

class App extends React.Component {
  constructor(props) {
    super(props);

    this.username = React.createRef();
    this.password = React.createRef();
    this.state = {
      errors: []
    };
  }

  handleSubmit = (event) => {
    event.preventDefault();
    const username = this.username.current.value;
    const password = this.password.current.value;
    const errors = this.handleValidation(username, password);

    if (errors.length > 0) {
      this.setState({ errors });
      return;
    }
    // submit data
  };

  handleValidation = (username, password) => {
    const errors = [];
    if (username.length === 0) {
      errors.push("Username cannot be empty");
    }

    if (password.length < 6) {
      errors.push("Password should be at least 6 characters long");
    }

    return errors;
  };

  render() {
    const { errors } = this.state;
    return (
      <div>
        <h1>React Ref Example</h1>
        <form onSubmit={this.handleSubmit}>
          {errors.map(error => <p key={error}>{error}</p>)}
          <div>
            <label>Username:</label>
            <input type="text" ref={this.username} />
          </div>
          <div>
            <label>Password:</label>
            <input type="text" ref={this.password} />
          </div>
          <div>
            <button>Submit</button>
          </div>
        </form>
      </div>
    );
  }
}


ReactDOM.render(<App />, document.getElementById("root"));

They use refs for the form validation, but what is the point ? Is not it better to use state for this purpose ? Thanks for any tips!

Noob
  • 2,247
  • 4
  • 20
  • 31

1 Answers1

-1

Refs can help you to retrieve the id,name or change the value of specific element

Anas Mirza
  • 19
  • 1
  • 7
  • It seems to me that i can do it with state , could you elaborate or provide a practical example where i do need to use refs to achieve something ? – Noob Aug 11 '19 at 04:48
  • this link will help you alot https://medium.com/@mrewusi/a-gentle-introduction-to-refs-in-react-f407101a5ea6 – Anas Mirza Aug 11 '19 at 04:54