1import React, {useRef, useEffect} from "react";
2
3export default function (props) {
4 // Initialized a hook to hold the reference to the title div.
5 const titleRef = useRef();
6
7 useEffect(function () {
8 setTimeout(() => {
9 titleRef.current.textContent = "Updated Text"
10 }, 2000); // Update the content of the element after 2seconds
11 }, []);
12
13 return <div className="container">
14 {/** The reference to the element happens here **/ }
15 <div className="title" ref={titleRef}>Original title</div>
16 </div>
17}
1import React, { useRef } from 'react';
2
3function TextInputWithFocusButton() {
4 const inputEl = useRef(null);
5 const onButtonClick = () => {
6 // `current` points to the mounted text input element
7 inputEl.current.focus();
8 };
9 return (
10 <>
11 <input ref={inputEl} type="text" />
12 <button onClick={onButtonClick}>Focus the input</button>
13 </>
14 );
15}
1import React, { useEffect, useRef } from 'react';
2
3const fooComponent = props => {
4 const inputBtnRef = useRef(null);
5 useEffect(() => {
6 //Add the ref action here
7 inputBtnRef.current.focus();
8 });
9
10 return (
11 <div>
12 <input
13 type="text"
14 ref={inputBtnRef}
15 />
16 </div>
17 );
18}
1function TextInputWithFocusButton() {
2 const inputEl = useRef(null);
3 const onButtonClick = () => {
4 // `current` points to the mounted text input element
5 inputEl.current.focus();
6 };
7 return (
8 <>
9 <input ref={inputEl} type="text" />
10 <button onClick={onButtonClick}>Focus the input</button>
11 </>
12 );
13}
1const refContainer = useRef(initialValue);
2//useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue).
3//The returned object will persist for the full lifetime of the component.