In which situation would you use refs in React?
Answer
Refs in React are used to access the DOM nodes or components directly. They provide a way to interact with the underlying DOM elements in a React component. Refs are used in situations where we need to access the DOM nodes or components directly, for example, to get the value of an input field, to focus on an input field, or to trigger an animation on a component. Refs are also used to integrate with third-party libraries that require direct access to the DOM.
One common use case for refs is in forms. When we need to get the value of an input field, we can use a ref to access the DOM node directly and get its value. For example, if we have a form with an input field for the user's name, we can use a ref to get the value of the input field when the form is submitted. This allows us to handle form data in a more flexible way than using controlled components.
Another use case for refs is in animations. When we need to trigger an animation on a component, we can use a ref to access the underlying DOM node and apply the animation directly. For example, if we have a button that triggers an animation when clicked, we can use a ref to access the button's DOM node and apply the animation directly to it. This allows us to create more complex and dynamic animations than using CSS alone.
class MyForm extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
handleSubmit = (event) => {
event.preventDefault();
const name = this.inputRef.current.value;
console.log(name);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label>Name:</label>
<input type="text" ref={this.inputRef} />
<button type="submit">Submit</button>
</form>
);
}
}
In the example above, we create a ref using the React.createRef()
method and attach it to the input field using the ref
attribute. When the form is submitted, we get the value of the input field using the ref's current
property. This allows us to handle form data in a more flexible way than using controlled components.
Related React job interview questions
How would you use validation on props?
React JuniorWhy would you use super constructors with props arguments in React?
React JuniorWhy do you need to use refs in React?
React JuniorWhat are refs in React?
React JuniorWhat is better in React? Functional or class component?
React Junior