useref react hooks example
Example 1: 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 2: 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 3: 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 4: 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>
</>
);
}
Example 5: what does useref do react
const refContainer = useRef(initialValue);