How to access DOM elements in React JS?
var number=document.getElementById("inputEmail1").value;
The above code will not work while working with React JS as we are not directly dealing with the document object. Then how we will access the DOM elements in React.
By using Ref we can access all DOM elements in React JS. Below is the code snippet.
import React, { Component } from 'react';
class LoginForm extends Component {
username = React.createRef();
state = {}
handleSubmit = e => {
// Call the server
e.preventDefault();
const username = this.username.current.value;
alert(username);
};
render() {
return (
<div>
<div class="form-row">
<form onSubmit={this.handleSubmit}>
<div className="form-group col-md-12">
<label htmlFor="username">Email address</label>
<input ref={this.username} type="email" className="form-control" id="username" aria-describedby="emailHelp" placeholder="Enter email" />
<small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div className="form-group col-md-12">
<label htmlForfor="InputPassword1">Password</label>
<input type="password" className="form-control" id="InputPassword1" placeholder="Password" />
</div>
<div className="form-check">
<input type="checkbox" className="form-check-input" id="Check1" />
<label className="form-check-label" for="Check1">Check me out</label>
</div>
<button type="submit" className="btn btn-primary m-2">Submit</button>
</form>
</div>
</div>
);
}
}
export default LoginForm;
Out Put:
There are different ways to access the DOM elements. But remember do not use ref unless until it is required. Try to avoid using ref for better performance. Whenever you are dealing with third-party libraries such as animation.
No comments:
Post a Comment