Accessing Refs in React
In React, when a ref is passed to an element in render using the ref attribute, the underlying DOM element or React component becomes accessible at the current property of the ref.
const node = this.myCallRef.current;
Now, we are going to see how we can use refs in our code which will help you to understand the use case of refs better.
Example
In this example, we use the target value of event e, for getting the value.
// Filename - App.js
// without refs
class App extends React.Component {
constructor() {
super();
this.state = { sayings: "" };
}
update(e) {
this.setState({ sayings: e.target.value });
}
render() {
return (
<div>
Mukul Says{" "}
<input
type="text"
onChange={this.update.bind(this)}
/>
<br />
<em>{this.state.sayings}</em>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
Output:
ReactJS Refs
ReactJS Refs are used to access and modify the DOM elements in the React Application. It creates a reference to the elements and uses it to modify them.
Table of Content
- What are React refs ?
- Creating refs in React
- Accessing Refs in React
- When to use refs
- When not to use refs