Aimed functionality:
When a user clicks a button, a list shows. When he clicks outside the list, it closes and the button should receive focus. (following accessibility guidelines)
What I tried:
const hideList = () => {
// This closes the list
setListHidden(true);
// This takes a ref, which is forwarded to <Button/>, and focuses it
button.current.focus();
}
<Button
ref={button}
/>
Problem:
When I examined the scope of hideList function, found that ref gets the proper reference to button every where but inside the click event handler, it's {current: null}.
The console outputs: Cannot read property 'focus' of null
Example:
https://codepen.io/moaaz_bs/pen/zQjoLK
- click on the button and then click outside and review the console.
Since you are already using hooks in your App, the only change you need to make is to use
useRefinstead ofcreateRefto generate a ref to the list.Working demo
The reason that you need it is because on every render of your Functional component, a new ref will be generated if you make use of
React.createRefwhereasuseRefis implemented such that it generates a ref when its called the first time and returns the same reference anytime in future re-renders.