Reactjs this.refs vs document.getElementById

If I have only basic forms, should I still have this.refs or just go with document.getElementById ?

By means I mean something like:

 export default class ForgetPasswordComponent extends React.Component { constructor(props) { super(props); this.handleSendEmail = this.handleSendEmail.bind(this); } handleSendEmail(e) { e.preventDefault(); // this.refs.email.value // document.getElementById('email').value } render() { <form onSubmit={this.handleSendEmail}> <input id="email" ref="email" type="text" /> <input type="submit" /> </form> } } 

Is there a drawback to using one over the other?

+5
source share
1 answer

Refs are generally better than document.getElementById because it matches the rest of your reaction code more.

In response, each component class can have multiple component instances.
And as @Isuru notes in the comments: using id is dangerous, because the reaction does not prevent you from having multiple forms on 1 page, and then your DOM contains several inputs with the same identifier. And this is not allowed.

Another advantage of using links is that by design, you can refer to ref only in the context where you define it. This forces you to use the details and status (and possibly stores) if you need to access information outside this context.
And this is an advantage because it is likely that you will break the unidirectional data stream, which will make your code less manageable.

NB: in almost all cases refs can be avoided altogether. The Netflix development principle for use is not referenced, ever , as explained by Steve McGuire (senior user interface engineer at Netflix) in this video from the conf 2016 reactor (9: 58 m in video).
In your case, this would mean putting the email input value in the form state, adding the onChange handler, and using the status value in the submit event.

+7
source

All Articles