So I decidet to rewrite my React Class Component into React Hook Component, And in my Class Component I did
<canvas ref='canvas'></canvas>
This approach didn't work anymore. How should I use refs then? In documentation only said that refs are still work.
Thank you!
Refs provide a way to access DOM nodes or React elements created in the render method. In the typical React dataflow, props are the only way that parent components interact with their children. To modify a child, you re-render it with new props.
In order to work with refs in React you need to first initialize a ref which is what the useRef hook is for. This hook is very straightforward, and takes an initial value as the only argument. This hook then returns a ref for you to work with.
The useRef Hook allows you to persist values between renders. It can be used to store a mutable value that does not cause a re-render when updated. It can be used to access a DOM element directly.
Refs are a function provided by React to access the DOM element and the React element that you might have created on your own. They are used in cases where we want to change the value of a child component, without making use of props and all.
With hooks you can use the useRef
hook.
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>
</>
);
}
look at the useRef
docs here:
https://reactjs.org/docs/hooks-reference.html#useref
In case you would like to use refs inside a map function:
export default () => {
const items = ['apple', 'orange', 'mango'];
// 1) create an array of refs
const itemRefs = useRef(items.map(() => React.createRef()));
useEffect(() => {
// 3) access a ref, for example 0
itemRefs.current[0].current.focus()
}, []);
return (
<ul>
{items.map((item, i) => (
// 2) attach ref to each item
<li key={item} ref={itemRefs.current[i]}>{item}</li>
))}
</ul>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With