Creating refs in ReactJS is very simple. Refs are generally used for the following purposes:
- Managing focus, text selection, or media playback.
- Triggering imperative animations.
- Integrating with third-party DOM libraries.
Note: You should avoid using refs for anything that can be done declaratively.
The following examples are based on only Functional-Components but you are free to use Class-Components as well.
Method 1: Using React.createRef(). It was introduced in React 16.3.
- Create a ref variable using React.createRef()
- Use the element’s ref attribute to attach the ref variable
Filename: App.js
Javascript
import * as React from "react" ;
const App = () => {
const textInputRef = React.createRef();
const textInputFocusHandler = () => {
textInputRef.current.focus();
};
return (
<div>
{ }
<input ref={textInputRef} type= "text"
placeholder= "Enter something" />
{ }
<button onClick={textInputFocusHandler}>
Click me to focus input
</button>
</div>
);
};
export default App;
|
Method 2: Using useRef() hook.
- Create a ref variable using React.useRef()
- Use the element’s ref attribute to attach the ref variable
- The benefit of using useRef() over createRef() is that it’s handy for keeping any mutable value around similar to how you’d use instance fields in classes.
- useRef() also takes an initial value.
Filename: App.js
Javascript
import * as React from "react" ;
const App = () => {
const textInputRef = React.useRef( null );
const textInputFocusHandler = () => {
textInputRef.current.focus();
};
return (
<div>
{ }
<input ref={textInputRef} type= "text"
placeholder= "Enter something" />
{ }
<button onClick={textInputFocusHandler}>
Click me to focus input
</button>
</div>
);
};
export default App;
|
Method 3: Using callback ref. This method was used prior to React 16.3. So if you are using React < 16.3 use this method.
Creating ref using this method is a bit different than the other two methods. Instead of passing a ref attribute created using createRef() or useRef() we pass a function. The function receives the React element or HTML DOM element as an argument, which can be used.
Filename: App.js
Javascript
import * as React from "react" ;
const App = () => {
let textInputRef = null ;
const setTextInputRef = (element) => {
textInputRef = element;
};
const textInputFocusHandler = () => {
if (textInputRef) {
textInputRef.focus();
}
};
return (
<div style={{ padding: 16 }}>
{
}
<input
style={{ display: "block" }}
ref={setTextInputRef}
type= "text"
placeholder= "Enter something"
/>
{
}
<button onClick={textInputFocusHandler}>
Click me to focus input
</button>
</div>
);
};
export default App;
|
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output:
