How to use callback ref In ReactJS
This method was used before React 16.3 version. So if you are using React<16.3 you will use this method. In this method, we pass a function instead of passing a ref attribute that is created by createRef() or useRef(). The function receives the React element or HTML DOM element as an argument, which can be used.
Syntax:
let textInput = null;
// Callback function that will set ref for input field
const setTextInputRef = (element) => {
textInputRef = element;
};
Example: This example implements refs by using createRef method.
Javascript
// Filname - App.js import * as React from "react" ; const App = () => { // Creating textInputRef variable const textInputRef = React.createRef(); // This method will be used to focus textInput // and give background color to textInput field const textInputFocusHandler = () => { // Focusing input element textInputRef.current.focus(); // Giving background color to input element textInputRef.current.style.background = "green" ; }; return ( <div style={{ textAlign: "center" , margin: "auto" }} > <h1 style={{ color: "green" }}> w3wiki </h1> <h3>React Example of Using Refs</h3> { /* Attaching ref variable using element's ref attribute */ } <input ref={textInputRef} type= "text" /> { /* Attaching textInputFocusHandler method to button click */ } <button onClick={textInputFocusHandler}> Focus </button> </div> ); }; export default App; |
Steps to Run: Use this command in the terminal inside the project directory.
npm start
Output: This output will be visible on the http://localhost:3000/ on the browser window.
What is significance of refs in ReactJS ?
Refs are a function provided by React to access the DOM element and the React element that you might have created on your own. They are used in cases where we want to change the value of a child component, without making use of props and all. They also provide us with good functionality as we can use callbacks with them. We can create a Ref by the following three methods:
Table of Content
- Using React.createRef()
- Using useRef() hook
- Using callback ref
- Significance of Refs in React JS:
Contact Us