Welcome to our in-depth React JS tutorial on Typing Refs! 🚀
In this lesson, we will explore how to access DOM elements and React components' instances directly using refs. Let's dive in!
Refs are a way to access the DOM nodes or React elements created in the render method. They provide a way to access the underlying DOM node or instance of a React component.
There are cases where you may need to access the underlying DOM node or instance of a React component. Here are a few examples:
React provides two types of refs:
React.createRef(): This is the simplest way to create a ref. It returns a ref object with a current property that can hold a DOM node or null.forwardRef: This is a higher-order component used when you want to pass a ref to a child component.Let's see how we can use refs in functional components using the React.createRef() method.
import React, { useState, createRef } from 'react';
function FocusInput() {
const inputRef = createRef();
const onFocus = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={onFocus}>Focus the input</button>
</div>
);
}In the above example, we create a ref using createRef() and assign it to the input element. We also define an onFocus function that sets the focus on the input when the button is clicked.
In class components, you can use refs in the same way as functional components, but with a slightly different syntax.
class FocusInput extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
focusInput() {
this.inputRef.current.focus();
}
render() {
return (
<div>
<input ref={this.inputRef} type="text" />
<button onClick={() => this.focusInput()}>Focus the input</button>
</div>
);
}
}In the above example, we create a ref in the constructor and assign it to the input element. We also define a focusInput method that sets the focus on the input when called.
When using refs in child components, you can access them in the parent component using the React.forwardRef method.
import React, { useState, createRef, forwardRef } from 'react';
const FocusInput = forwardRef((props, ref) => {
const inputRef = React.useRef(null);
const onFocus = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={ref} type="text" />
<button onClick={onFocus}>Focus the input</button>
</div>
);
});
function App() {
const inputRef = React.useRef(null);
const setInputRef = (node) => {
inputRef.current = node;
};
return (
<div>
<FocusInput ref={setInputRef} />
<button onClick={() => inputRef.current.focus()}>
Focus the input from parent
</button>
</div>
);
}In the above example, we use forwardRef to pass the ref from the parent component to the child component. We then create a ref in the parent component and pass it as a prop to the child component. In the child component, we define a ref using React.useRef() and pass the parent's ref as a prop.
What is the purpose of using refs in React?
What are the two types of refs provided by React?