18. How do refs work in React and how do you use them in functional components?

Refs in React allow you to directly access DOM elements or component instances. Refs can be used to manage focus, select text, trigger animations, or integrate with external libraries.

Using refs in class components:

class MyComponent extends React.Component { constructor(props) { super(props); this.myRef = React.createRef(); } componentDidMount() { this.myRef.current.focus(); } render() { return <input ref={this.myRef} />; } }

Using refs in functional components with the useRef hook:

import React, { useRef, useEffect } from 'react'; function MyComponent() { const myRef = useRef(null); useEffect(() => { myRef.current.focus(); }, []); return <input ref={myRef} />; }

Refs are useful when you need to directly manipulate DOM elements or access input values in functional components.

devFlipCards 2024

Do you accept cookies?

Cookies are small amounts of data saved locally on you device, which helps our website - it saves your settings like theme or language. It helps in adjusting ads and in traffic analysis. By using this site, you consent cookies usage.