useRef example
/*
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>
</>
);
}
4
1
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 <div className="container">
{/** The reference to the element happens here **/ }
<div className="title" ref={titleRef}>Original title</div>
</div>
}
Thank you!
1
0
4.13
8
import React, { useRef, useEffect } from 'react';
function CountMyRenders() {
const countRenderRef = useRef(1);
useEffect(function afterRender() {
countRenderRef.current++; });
return (
<div>I've rendered {countRenderRef.current} times</div>
);
}
Thank you!
8
0
Are there any code examples left?
New code examples in category Javascript