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!