How to use React.createRef(). In ReactJS
- 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
Example: Below is the code example of the React.createRef().
Javascript
// Importing everything as React import * as React from "react" ; const App = () => { // Creating textInputRef variable const textInputRef = React.createRef(); // This method will be used to focus textInput const textInputFocusHandler = () => { // Focusing input element textInputRef.current.focus(); }; return ( <div> { /** Attaching ref variable using element's ref attribute */ } <input ref={textInputRef} type= "text" placeholder= "Enter something" /> { /** Attaching textInputFocusHandler method to button click */ } <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:
How to create refs in React JS?
React JS, a powerful and declarative JavaScript library for building user interfaces, provides a feature known as ârefsâ that allows developers to interact with the underlying DOM elements directly.
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:
Table of Content
- Using React.createRef()
- Using useRef() hook
- Using callback ref()
Contact Us