useref hook react js code example
Example 1: useref react
import React, {useRef, useEffect} from "react";
export default function (props) {
const titleRef = useRef();
useEffect(function () {
setTimeout(() => {
titleRef.current.textContent = "Updated Text"
}, 2000);
}, []);
return <div className="container">
{ }
<div className="title" ref={titleRef}>Original title</div>
</div>
}
Example 2: useRef() in react
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}