How to create refs in React?
How to create refs in React?
To create refs in React, you can use either the React.createRef() method for class components or the useRef hook for functional components. Here's how you can use each method:
React.createRef() in Class ComponentsIntroduced in React 16.3, React.createRef() creates a ref object that you can attach to React elements via the ref attribute. This method is typically used in class components. Here's an example:
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
// Create a ref object using React.createRef()
this.myRef = React.createRef();
}
render() {
return <div ref={this.myRef}>Hello, World!</div>;
}
}
export default MyComponent;
In this example, this.myRef is attached to a <div> element. Once the component mounts, this.myRef.current will point to the corresponding DOM node[3][7][10].
useRef Hook in Functional ComponentsThe useRef hook is part of React's Hooks API introduced in React 16.8. It works similarly to createRef but is used in functional components. Here's how you can use it:
import React, { useRef } from 'react';
function MyComponent() {
// Create a ref object using useRef()
const myRef = useRef(null);
return <div ref={myRef}>Hello, World!</div>;
}
export default MyComponent;
In this example, myRef is initialized ...
junior