...

/

Global Event Handling and Interactive UI

Global Event Handling and Interactive UI

Learn about how useRef proves beneficial for scenarios requiring precise control over DOM elements and addressing potential issues.

Reactivity with refs

A ref is powerful. Because React makes things very reactiveThe ability to automatically update and re-render components in response to changes in data or state., if we want to either disable this reactiveness or add a tweak to it, the ref gives us the opportunity to do that. We'll look into more examples of how it can be used to solve interesting problems in React.

Clicking outside the menu

Say we have a component, and we want to know when the user clicks outside of it. This is a very popular feature for a popup menu or a modal. Once the menu is visible, we want to dismiss it when the user clicks anywhere outside of it:

Press + to interact
Click outside to dismiss
Click outside to dismiss

Let's say we have a Menu component displaying a list of menu items:

const Menu = () => {
// State variable 'on' to control the visibility of the menu
const [on, setOOn] = useState(true);
// If 'on' is false, return null to render nothing
if (!on) return null;
// If 'on' is true, render the menu
return (
// Unordered list containing navigation items
<ul>
{/* Navigation items */}
<li>Home</li>
<li>Price</li>
<li>Produce</li>
<li>Support</li>
<li>About</li>
</ul>
);
}
A React component that conditionally renders a list of navigation items based on the state of a toggle

In the preceding code, an on state is created and set to true initially, making a list of the menu items visible. However, when we click outside of this list, we'd want to set on to false to hide it. For simplicity, here we define the on ...