/*
A common use case is to access a child imperatively:
*/
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
/**
* Accessing DOM elements
*
* Another useful application of the useRef() hook is to access DOM elements.
* This is performed in 3 steps:
*
* - Define the reference to access the element const elementRef = useRef();
* - Assign the reference to ref attribute of the element: <div ref={elementRef}></div>;
* - After mounting, elementRef.current points to the DOM element.
*/
import { useRef, useEffect } from 'react';
function AccessingElement() {
const elementRef = useRef();
useEffect(() => {
const divElement = elementRef.current;
console.log(divElement); // logs <div>I'm an element</div>
}, []);
return (
<div ref={elementRef}>
I'm an element
</div>
);
}
const refContainer = useRef(initialValue);
//useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue).
//The returned object will persist for the full lifetime of the component.
useRef is an kind of alternative to useState hook , with useRef you can get an reference to an element and than use the DOM/JS properties to modify it .
You can even call useRef as an tool which is used to apply all the DOM properties as you were doing in Javascript before coming to React.
If you use useRef than this apparoch is called un-controlled components.
class CustomTextInput extends React.Component {
constructor(props) {
super(props);
// create a ref to store the textInput DOM element
this.textInput = React.createRef();
this.focusTextInput = this.focusTextInput.bind(this);
}
focusTextInput() {
// Explicitly focus the text input using the raw DOM API
// Note: we're accessing "current" to get the DOM node
this.textInput.current.focus();
}
render() {
// tell React that we want to associate the <input> ref
// with the `textInput` that we created in the constructor
return (
<div>
<input
type="text"
ref={this.textInput} />
<input
type="button"
value="Focus the text input"
onClick={this.focusTextInput}
/>
</div>
);
}
}