Skip to content

Clicking Outside

In this challenge, you'll build a custom hook that allows us to run some code when the user clicks outside a particular DOM node.

Specifically, you'll use this hook to implement a popover that can be dismissed by clicking outside:

Difficulty

This is where things start to get a lot more difficult. This challenge touches on some of the most complex parts of working with modern React.

You may not be able to fully solve this problem, but as always, that's not really the most important thing. Most interviewers would be impressed even if you only get halfway through this challenge, but you're able to show your thought process and make some good progress.

Rules

  • You're allowed to google for general help (eg. looking up JavaScript methods), but please don't search for the full solution to this particular problem. The interviewer wants to see if you can work it out on your own!
  • No third-party packages.
  • You shouldn't have to disable any ESLint rules.

Playground

Code Playground

import React from 'react';

function App() {
const [isOpen, setIsOpen] = React.useState(false);

return (
<div className="wrapper">
<button
className="account-toggle-trigger"
aria-label="Toggle account dropdown"
onClick={() => setIsOpen(true)}
>
<img alt="" src="/img/avatars/005.png" />
</button>

{isOpen && <div className="popover">
<ul className="account-links">
<li>
<a href="/account">My Account</a>
</li>
<li>
<a href="/stats">Statistics</a>
</li>
<li>
<a href="/logout">Log out</a>
</li>
</ul>
</div>}
</div>
);
}

export default App;

My attempt