useRef react hooks code example
Example 1: useRef
/*
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 (
<>
>
);
}
Example 2: useref react
import React, {useRef, useEffect} from "react";
export default function (props) {
// Initialized a hook to hold the reference to the title div.
const titleRef = useRef();
useEffect(function () {
setTimeout(() => {
titleRef.current.textContent = "Updated Text"
}, 2000); // Update the content of the element after 2seconds
}, []);
return
{/** The reference to the element happens here **/ }
Original title
}
Example 3: useref in functional component
import React, { useRef } from 'react';
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
>
);
}
Example 4: react useref in useeffect
import React, { useEffect, useRef } from 'react';
const fooComponent = props => {
const inputBtnRef = useRef(null);
useEffect(() => {
//Add the ref action here
inputBtnRef.current.focus();
});
return (
);
}
Example 5: useRef() in react
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
// `current` points to the mounted text input element
inputEl.current.focus();
};
return (
<>
>
);
}
Example 6: what does useref do react
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.