react hooks useref code example
Example 1: react usestate
import React, { useState } from 'react';
function Example() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Example 2: useRef
function TextInputWithFocusButton() {
const inputEl = useRef(null);
const onButtonClick = () => {
inputEl.current.focus();
};
return (
<>
<input ref={inputEl} type="text" />
<button onClick={onButtonClick}>Focus the input</button>
</>
);
}
Example 3: 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 4: useref in functional component
import React, { useRef } from '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>
</>
);
}
Example 5: react useref in useeffect
import React, { useEffect, useRef } from 'react';
const fooComponent = props => {
const inputBtnRef = useRef(null);
useEffect(() => {
inputBtnRef.current.focus();
});
return (
<div>
<input
type="text"
ref={inputBtnRef}
/>
</div>
);
}
Example 6: 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>
</>
);
}