How to perform multiple actions when clicking on a button component? - javascript

I created a button in solid-js and I would like that when this button is clicked, a page is opened and the counter goes to zero. To perform these operations, I have already created two functions. I would like to ensure that when clicking this button that these two functions are called asynchronously. So I wrote the following code:
<button
onClick={[toggle, setNullCount]}
>
with functions to call toggle and setNullCount. However, I realized that when I click on the button, only the first declared function is called and I don't know how to allow two functions to be called on click.

Here is a solution
onClick={() => {toggle(); setNullCount()}}
when you want assign more than one action to trigger you must create a function which handles methods that will be performed as effect.

You need to create a single handler function that calls both handlers:
<button
onClick={() => {
toggle();
setNullCount();
}}
>

A wrapper function is not equivalent to adding multiple listeners and it is not always feasible, i.e when you want to handle each events differently.
An alternative could be adding listeners to the element using its reference:
import { onCleanup, onMount } from 'solid-js';
import { render } from 'solid-js/web'
const App = () => {
let el: HTMLButtonElement | undefined;
const handleOne = (event: any) => {
console.log(`Event One`);
};
const handleTwo = (event: any) => {
console.log(`Event Two`);
};
onMount(() => {
el?.addEventListener('click', handleOne);
el?.addEventListener('click', handleTwo);
});
onCleanup(() => {
el?.removeEventListener('click', handleOne);
el?.removeEventListener('click', handleTwo);
});
return (
<div>
<button ref={el}>Click</button>
</div>
)
};
render(App, document.body);
You can see the live demo: https://playground.solidjs.com/anonymous/86afc8e3-3574-40ed-88f7-2e5b467f6b9a
Element is guaranteed to exist inside onMount and onCleanup effects but I didn't want to suppress the type system by a non-null assertion so used optional chaining operator, ?.
Another alternative could be event delegation:
import { onCleanup, onMount } from 'solid-js';
import { render } from 'solid-js/web'
const App = () => {
const handleOne = (event: any) => {
console.log(`Event One`);
};
const handleTwo = (event: any) => {
console.log(`Event Two`);
};
onMount(() => {
document.body.addEventListener('click', handleOne);
document.body.addEventListener('click', handleTwo);
});
onCleanup(() => {
document.body.removeEventListener('click', handleOne);
document.body.removeEventListener('click', handleTwo);
});
return (
<div>
<button>Click</button>
</div>
)
};
render(App, document.body);
Click the link to see the live demo: https://playground.solidjs.com/anonymous/434364d4-c467-427f-8709-3e10557e0b9e
A third alternative could be using so called on:weirdEvent syntax:
import { render } from 'solid-js/web'
const App = () => {
const handleOne = (event: any) => {
console.log(`Event One`);
};
const handleTwo = (event: any) => {
console.log(`Event Two`);
};
return (
<div>
<button on:click={handleOne} on:click={handleTwo}>Click</button>
</div>
)
};
render(App, document.body);
For any other events, perhaps ones with unusual names, or ones you wish not to be delegated, there are the on namespace events. This attribute adds an event listener verbatim.
https://www.solidjs.com/docs/latest/api#on___oncapture___
You can find the live demo: https://playground.solidjs.com/anonymous/30c32d5b-3185-45ab-987d-15f2bf9c8f98
A fourth alternative could be using a custom directive. A custom directive receives the element when the element gets created in the DOM. So, you can attach the listener on the element itself or use event delegation. I will go with the former one here:
import { Accessor, onCleanup } from 'solid-js';
import { render } from 'solid-js/web';
interface Handlers {
handlerOne: (event: MouseEvent) => void;
handlerTwo: (event: MouseEvent) => void;
}
export const multipleHandlers = (el: HTMLButtonElement, args: Accessor<Handlers>) => {
el.addEventListener("click", args().handlerOne);
el.addEventListener("click", args().handlerTwo);
onCleanup(() => el.removeEventListener("click", args().handlerOne));
onCleanup(() => el.removeEventListener("click", args().handlerTwo));
}
declare module "solid-js" {
namespace JSX {
interface Directives {
multipleHandlers: Handlers;
}
}
}
const App = () => {
const handlerOne = (event: any) => {
console.log(`Event One`);
};
const handlerTwo = (event: any) => {
console.log(`Event Two`);
};
return (
<div>
<button use:multipleHandlers={{ handlerOne, handlerTwo }}>Click</button>
</div>
)
}
render(App, document.body);
https://playground.solidjs.com/anonymous/d6cbfe71-d657-4749-9126-a5fc5984a334
Explicit being better than implicit, I advice you to use any of the above methods over a custom directive. Custom directives could be a good alternative only when you find yourself in need to add multiple listeners to the same element frequently.

Related

How to pass event from component to nested function?

I've got two splitted functions and I need to pass a value from one to the other, which I'm doing like shown below. What is the difference between const handleClick = icon.onClick(category) and const handleClick = () => icon.onClick(category)?
And how do I pass the event from the component to the handleClick() function?
export const useCategories = () => {
const handleClick = (category, something) => {
event.stopPropagation() // <-- 3. How to get event?
console.log(category, something) // <-- 4. Get every value
}
return {
icon: {
onClick: (category) => handleClick(category, 'anything') // <-- 2. add second var value
}
}
}
export const Categories = () => {
const { icon } = useCategories()
return (
<div>
{categories.map((category) => {
const handleClick = icon.onClick(category) // <-- 1. pass category value
return <Icon onClick={handleClick} />)}
}
</div>
)
}
You'll need to proxy the event object through on all click handlers. I like to use curried functions to make attaching the click handler a little simpler. Don't forget to add a react key to the mapped icons.
export const useCategories = () => {
const handleClick = (event, category, something) => {
event.stopPropagation();
console.log(category, something);
};
return {
icon: {
// curried function to receive category and return onClick handler
onClick: category => event => handleClick(event, category, 'anything'),
}
}
}
export const Categories = () => {
const { icon } = useCategories();
return (
<div>
{categories.map((category, index) => (
<Icon
key={index}
onClick={icon.onClick(category)} // <-- set category
/>
)
</div>
);
}
The onevent handlers are properties on certain DOM elements to manage how that element reacts to events.
When the event handler is specified as an HTML attribute, the specified code is wrapped into a function with the following parameters:
event — for all event handlers except onerror.
event, source, lineno,colno, and error for the onerror event handler.
Note that the event parameter actually contains the error
message as a string.
When the event handler is invoked, the this keyword inside the handler is set to the DOM element on which the handler is registered. For more details, see, see the this keyword documentation.
if you want more see, this
but in your code, you need to add this
<Icon onClick={(event) => icon.onClick(event, category, ...rest)} />
As you want to pass the event and category to the click handler, modify the function passed to onClick to pass the args.
export const useCategories = () => {
const handleClick = (event, ...rest) => {
event.stopPropagation();
console.log(rest);
};
return {
icon: {
onClick: (event, category) => handleClick(event, category, 'anything'),
},
};
};
export const Categories = () => {
const { icon } = useCategories();
return (
<div>
{categories.map((category) => {
return <Icon onClick={(event) => icon.onClick(event, category)} />;
})}
</div>
);
};
When you dont need to pass parametrs you use
onClick={func}
When you want to pass parametrs you use
onClick={() => func(someParmeter)}
To pass the event simply write
onClick={e => func(e)}

React dropdown toggles only once

I am trying to build React Dropdown component using useRef hook and Typescript:
It opens correctly and closes if I click toggle button once or click outside of it, but it will closed when I want to open it again. Any ideas ? Is this I am loosing ref referance somehow ?
Here is usage:
https://codesandbox.io/s/react-typescript-obdgs
import React, { useState, useRef, useEffect } from 'react'
import styled from 'styled-components'
interface Props {}
const DropdownMenu: React.FC<Props> = ({ children }) => {
const [menuOpen, toggleMenu] = useState<boolean>(false)
const menuContent = useRef<HTMLDivElement>(null)
useEffect(() => {
// console.log(menuOpen)
}, [menuOpen])
const showMenu = (event: React.MouseEvent) => {
event.preventDefault()
toggleMenu(true)
document.addEventListener('click', closeMenu)
}
const closeMenu = (event: MouseEvent) => {
const el = event.target
if (menuContent.current) {
if (el instanceof Node && !menuContent.current.contains(el)) {
toggleMenu(false)
document.removeEventListener('click', closeMenu)
}
}
}
return (
<div>
<button
onClick={(event: React.MouseEvent) => {
showMenu(event)
}}
>
Open
</button>
{menuOpen ? <div ref={menuContent}>{children}</div> : null}
</div>
)
}
export default DropdownMenu
If you click the button twice, you will not be able to open it again. If you click outside the button to close, it will work as expected.
This is probably because your showMenu callback is executed even when the menu is already shown, which results in multiple closeMenu event listeners being attached, which in turn leads to weird behaviour.
The closeMenu event listener should be created inside an effect, not in the showMenu callback.
const showMenu = (event: React.MouseEvent) => {
event.preventDefault()
toggleMenu(true)
}
// closeMenu is the same
const closeMenu = (event: MouseEvent) => {
const el = event.target
if (menuContent.current) {
if (el instanceof Node && !menuContent.current.contains(el)) {
toggleMenu(false)
document.removeEventListener('click', closeMenu)
}
}
}
useEffect(() => {
if (!menuOpen) {
return
}
document.addEventListener('click', closeMenu)
return () => {
document.removeEventListener('click', closeMenu)
}
}, [menuOpen])
useEffect is really cool - the returned function where the event listener is removed will be called both when menuOpen is changed, and when the component is unmounted. In your previous code, if the component would be unmounted, the event listener would not be removed.
The problem comes from your onClick on the button. You are calling, showMenu every time you click on the button, so you are adding new event listener each time.
You don't want to call showMenu if the menu is already shown, so a fix can be :
<button onClick={(event: React.MouseEvent) => {
if (!menuOpen) showMenu(event);
}}>

Keydown/up events with React Hooks not working properly

I'm trying to create arrow based keyboard controls for a game I'm working on. Of course I'm trying to stay up to date with React so I wanted to create a function component and use hooks. I've created a JSFiddle for my buggy component.
It's almost working as expected, except when I press a lot of the arrow keys at the same time. Then it seems like some keyup events aren't triggered. It could also be that the 'state' is not updated properly.
Which I do like this:
const ALLOWED_KEYS = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']
const [pressed, setPressed] = React.useState([])
const handleKeyDown = React.useCallback(event => {
const { key } = event
if (ALLOWED_KEYS.includes(key) && !pressed.includes(key)) {
setPressed([...pressed, key])
}
}, [pressed])
const handleKeyUp = React.useCallback(event => {
const { key } = event
setPressed(pressed.filter(k => k !== key))
}, [pressed])
React.useEffect(() => {
document.addEventListener('keydown', handleKeyDown)
document.addEventListener('keyup', handleKeyUp)
return () => {
document.removeEventListener('keydown', handleKeyDown)
document.removeEventListener('keyup', handleKeyUp)
}
})
I have the idea that I'm doing it correctly, but being new to hooks it is very likely that this is where the problem is. Especially since I've re-created the same component as a class based component:
https://jsfiddle.net/vus4nrfe/
And that seems to work fine...
There are 3 key things to do to make it work as expected just like your class component.
As others mentioned for useEffect you need to add an [] as a dependency array which will trigger only once the addEventLister functions.
The second thing which is the main issue is that you are not mutating the pressed array's previous state in functional component as you did in class component, just like below:
// onKeyDown event
this.setState(prevState => ({
pressed: [...prevState.pressed, key],
}))
// onKeyUp event
this.setState(prevState => ({
pressed: prevState.pressed.filter(k => k !== key),
}))
You need to update in functional one as the following:
// onKeyDown event
setPressedKeys(previousPressedKeys => [...previousPressedKeys, key]);
// onKeyUp event
setPressedKeys(previousPressedKeys => previousPressedKeys.filter(k => k !== key));
The third thing is that the definition of the onKeyDown and onKeyUp events have been moved inside of useEffect so you don't need to use useCallback.
The mentioned things solved the issue on my end. Please find the following working GitHub repository what I've made which works as expected:
https://github.com/norbitrial/react-keydown-useeffect-componentdidmount
Find a working JSFiddle version if you like it better here:
https://jsfiddle.net/0aogqbyp/
The essential part from the repository, fully working component:
const KeyDownFunctional = () => {
const [pressedKeys, setPressedKeys] = useState([]);
useEffect(() => {
const onKeyDown = ({key}) => {
if (Consts.ALLOWED_KEYS.includes(key) && !pressedKeys.includes(key)) {
setPressedKeys(previousPressedKeys => [...previousPressedKeys, key]);
}
}
const onKeyUp = ({key}) => {
if (Consts.ALLOWED_KEYS.includes(key)) {
setPressedKeys(previousPressedKeys => previousPressedKeys.filter(k => k !== key));
}
}
document.addEventListener('keydown', onKeyDown);
document.addEventListener('keyup', onKeyUp);
return () => {
document.removeEventListener('keydown', onKeyDown);
document.removeEventListener('keyup', onKeyUp);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return <>
<h3>KeyDown Functional Component</h3>
<h4>Pressed Keys:</h4>
{pressedKeys.map(e => <span key={e} className="key">{e}</span>)}
</>
}
The reason why I'm using // eslint-disable-next-line react-hooks/exhaustive-deps for the useEffect is because I don't want to reattach the events every single time once the pressed or pressedKeys array is changing.
I hope this helps!
User #Vencovsky mentioned the useKeyPress recipe by Gabe Ragland. Implementing this made everything work as expected. The useKeyPress recipe:
// Hook
const useKeyPress = (targetKey) => {
// State for keeping track of whether key is pressed
const [keyPressed, setKeyPressed] = React.useState(false)
// If pressed key is our target key then set to true
const downHandler = ({ key }) => {
if (key === targetKey) {
setKeyPressed(true)
}
}
// If released key is our target key then set to false
const upHandler = ({ key }) => {
if (key === targetKey) {
setKeyPressed(false)
}
}
// Add event listeners
React.useEffect(() => {
window.addEventListener('keydown', downHandler)
window.addEventListener('keyup', upHandler)
// Remove event listeners on cleanup
return () => {
window.removeEventListener('keydown', downHandler)
window.removeEventListener('keyup', upHandler)
}
}, []) // Empty array ensures that effect is only run on mount and unmount
return keyPressed
}
You can then use that "hook" as follows:
const KeyboardControls = () => {
const isUpPressed = useKeyPress('ArrowUp')
const isDownPressed = useKeyPress('ArrowDown')
const isLeftPressed = useKeyPress('ArrowLeft')
const isRightPressed = useKeyPress('ArrowRight')
return (
<div className="keyboard-controls">
<div className={classNames('up-button', isUpPressed && 'pressed')} />
<div className={classNames('down-button', isDownPressed && 'pressed')} />
<div className={classNames('left-button', isLeftPressed && 'pressed')} />
<div className={classNames('right-button', isRightPressed && 'pressed')} />
</div>
)
}
Complete fiddle can be found here.
The difference with my code is that it use hooks and state per key instead of all the keys at once. I'm not sure why that would matter though. Would be great if somebody could explain that.
Thanks to everyone who tried to help and made the hooks concept clearer for me. And thanks for #Vencovsky for pointing me to the usehooks.com website by Gabe Ragland.
React.useEffect(() => {
document.addEventListener('keydown', handleKeyDown)
document.addEventListener('keyup', handleKeyUp)
return () => {
document.removeEventListener('keydown', handleKeyDown)
document.removeEventListener('keyup', handleKeyUp)
}
}, [handleKeyDown, handleKeyUp]); // <---- Add this deps array
You need to add the handlers as dependencies to the useEffect, otherwise it gets called on every render.
Also, make sure your deps array is not empty [], because your handlers could change based on the value of pressed.
All the solutions I found were pretty bad. For instance, the solutions in this thread only allow you to hold down 2 buttons, or they simply don't work like a lot of the use-hooks libraries.
After working on this for a long time with #asafaviv from #Reactiflux I think this is my favorite solution:
import { useState, useLayoutEffect } from 'react'
const specialKeys = [
`Shift`,
`CapsLock`,
`Meta`,
`Control`,
`Alt`,
`Tab`,
`Backspace`,
`Escape`,
]
const useKeys = () => {
if (typeof window === `undefined`) return [] // Bail on SSR
const [keys, setKeys] = useState([])
useLayoutEffect(() => {
const downHandler = ({ key, shiftKey, repeat }) => {
if (repeat) return // Bail if they're holding down a key
setKeys(prevKeys => {
return [...prevKeys, { key, shiftKey }]
})
}
const upHandler = ({ key, shiftKey }) => {
setKeys(prevKeys => {
return prevKeys.filter(k => {
if (specialKeys.includes(key))
return false // Special keys being held down/let go of in certain orders would cause keys to get stuck in state
return JSON.stringify(k) !== JSON.stringify({ key, shiftKey }) // JS Objects are unique even if they have the same contents, this forces them to actually compare based on their contents
})
})
}
window.addEventListener(`keydown`, downHandler)
window.addEventListener(`keyup`, upHandler)
return () => {
// Cleanup our window listeners if the component goes away
window.removeEventListener(`keydown`, downHandler)
window.removeEventListener(`keyup`, upHandler)
}
}, [])
return keys.map(x => x.key) // return a clean array of characters (including special characters 🎉)
}
export default useKeys
I believe you're Breaking the Rules of Hooks:
Do not call Hooks inside functions passed to useMemo, useReducer, or useEffect.
You're calling the setPressed hook inside a function passed to useCallback, which basically uses useMemo under the hood.
useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).
https://reactjs.org/docs/hooks-reference.html#usecallback
See if removing the useCallback in favor of a plain arrow function solves your problem.
useEffect runs on every render, resulting on adding/removing your listeners on each keypress. This could potential lead to a key press/release without a listener attached.
Suppling an empty array [] as second parameter to useEffect, React will know that this effect does not depend on any of the props/state values so it never needs to re-run, attaching and cleaning up your listeners once
React.useEffect(() => {
document.addEventListener('keydown', handleKeyDown)
document.addEventListener('keyup', handleKeyUp)
return () => {
document.removeEventListener('keydown', handleKeyDown)
document.removeEventListener('keyup', handleKeyUp)
}
}, [])

React custom synthetic event

I would like to create a custom synthetic event so that I can conditionally attach a handler (either a touchstart or click), based on a configuration option
However, I cannot seem to find any information on how this can be done
Ideally I would like the below (the onTap attribute)
<Button onTap={someHandler} title="Register" />
And then the onTap would attach the handler either on touchstart or click or any event I define in a config
Is this possible?
Is it possible to define a custom attribute that will hook on every component?
Regards
You could try something like this:
const W = (() => {
// all elements supported by React
const names = 'a|abbr|address|area|article|aside|audio|b|base|bdi|bdo|big|blockquote|body|br|button|canvas|caption|cite|code|col|colgroup|data|datalist|dd|del|details|dfn|dialog|div|dl|dt|em|embed|fieldset|figcaption|figure|footer|form|h1|h2|h3|h4|h5|h6|head|header|hgroup|hr|html|i|iframe|img|input|ins|kbd|keygen|label|legend|li|link|main|map|mark|menu|menuitem|meta|meter|nav|noscript|object|ol|optgroup|option|output|p|param|picture|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|source|span|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|u|ul|var|video|wbr|circle|clipPath|defs|ellipse|g|image|line|linearGradient|mask|path|pattern|polygon|polyline|radialGradient|rect|stop|svg|text|tspan'.split('|')
const res = {}
for (const El of names) {
res[El] = ({ onTap, ...props }) => {
onTap = onTap || x=>x
props.onClick = props.onClick || x => x
props.onTouchStart = props.onTouchStart || x => x
<El {...props} onClick={(...args) => {onTap(...args); props.onClick(...args)} onTouchStart={(...args) => {onTap(...args); props.onTouchStart(...args)} />
}
}
return res;
})()
<W.button onTap={() => alert('hi')} />
This will add the onTap handler to both the onClick and onTouchStart events of any element.
A similar technique can be used to wrap composite components.
To wrap every component, you need to wrap React.createElement.
Warning: I make no guarantees about if this will work. It is probably a very bad idea, and should not be used in a library.
const _ce = React.createElement.bind(React)
React.createElement = (name, props, ...args) => {
if (!props) {
return _ce(name, props, ...args)
}
const { onTap, ...newProps } = props
if (onTap) {
if (props.onClick) {
newProps.onClick = (...args) => {
props.onClick(...args)
onTap(...args)
}
} else {
newProps.onClick = onTap
}
if (props.onTouchStart) {
newProps.onTouchStart = (...args) => {
props.onTouchStart(...args)
onTap(...args)
}
} else {
newProps.onTouchStart = onTap
}
}
return _ce(name, newProps, ...args)
}

Detect click outside React component

I'm looking for a way to detect if a click event happened outside of a component, as described in this article. jQuery closest() is used to see if the target from a click event has the dom element as one of its parents. If there is a match the click event belongs to one of the children and is thus not considered to be outside of the component.
So in my component, I want to attach a click handler to the window. When the handler fires I need to compare the target with the dom children of my component.
The click event contains properties like "path" which seems to hold the dom path that the event has traveled. I'm not sure what to compare or how to best traverse it, and I'm thinking someone must have already put that in a clever utility function... No?
The following solution uses ES6 and follows best practices for binding as well as setting the ref through a method.
To see it in action:
Hooks Implementation
Class Implementation After React 16.3
Class Implementation Before React 16.3
Hooks Implementation:
import React, { useRef, useEffect } from "react";
/**
* Hook that alerts clicks outside of the passed ref
*/
function useOutsideAlerter(ref) {
useEffect(() => {
/**
* Alert if clicked on outside of element
*/
function handleClickOutside(event) {
if (ref.current && !ref.current.contains(event.target)) {
alert("You clicked outside of me!");
}
}
// Bind the event listener
document.addEventListener("mousedown", handleClickOutside);
return () => {
// Unbind the event listener on clean up
document.removeEventListener("mousedown", handleClickOutside);
};
}, [ref]);
}
/**
* Component that alerts if you click outside of it
*/
export default function OutsideAlerter(props) {
const wrapperRef = useRef(null);
useOutsideAlerter(wrapperRef);
return <div ref={wrapperRef}>{props.children}</div>;
}
Class Implementation:
After 16.3
import React, { Component } from "react";
/**
* Component that alerts if you click outside of it
*/
export default class OutsideAlerter extends Component {
constructor(props) {
super(props);
this.wrapperRef = React.createRef();
this.handleClickOutside = this.handleClickOutside.bind(this);
}
componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
/**
* Alert if clicked on outside of element
*/
handleClickOutside(event) {
if (this.wrapperRef && !this.wrapperRef.current.contains(event.target)) {
alert("You clicked outside of me!");
}
}
render() {
return <div ref={this.wrapperRef}>{this.props.children}</div>;
}
}
Before 16.3
import React, { Component } from "react";
/**
* Component that alerts if you click outside of it
*/
export default class OutsideAlerter extends Component {
constructor(props) {
super(props);
this.setWrapperRef = this.setWrapperRef.bind(this);
this.handleClickOutside = this.handleClickOutside.bind(this);
}
componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
/**
* Set the wrapper ref
*/
setWrapperRef(node) {
this.wrapperRef = node;
}
/**
* Alert if clicked on outside of element
*/
handleClickOutside(event) {
if (this.wrapperRef && !this.wrapperRef.contains(event.target)) {
alert("You clicked outside of me!");
}
}
render() {
return <div ref={this.setWrapperRef}>{this.props.children}</div>;
}
}
I was stuck on the same issue. I am a bit late to the party here, but for me this is a really good solution. Hopefully it will be of help to someone else. You need to import findDOMNode from react-dom
import ReactDOM from 'react-dom';
// ... ✂
componentDidMount() {
document.addEventListener('click', this.handleClickOutside, true);
}
componentWillUnmount() {
document.removeEventListener('click', this.handleClickOutside, true);
}
handleClickOutside = event => {
const domNode = ReactDOM.findDOMNode(this);
if (!domNode || !domNode.contains(event.target)) {
this.setState({
visible: false
});
}
}
React Hooks Approach (16.8 +)
You can create a reusable hook called useComponentVisible.
import { useState, useEffect, useRef } from 'react';
export default function useComponentVisible(initialIsVisible) {
const [isComponentVisible, setIsComponentVisible] = useState(initialIsVisible);
const ref = useRef(null);
const handleClickOutside = (event) => {
if (ref.current && !ref.current.contains(event.target)) {
setIsComponentVisible(false);
}
};
useEffect(() => {
document.addEventListener('click', handleClickOutside, true);
return () => {
document.removeEventListener('click', handleClickOutside, true);
};
}, []);
return { ref, isComponentVisible, setIsComponentVisible };
}
Then in the component you wish to add the functionality to do the following:
const DropDown = () => {
const { ref, isComponentVisible } = useComponentVisible(true);
return (
<div ref={ref}>
{isComponentVisible && (<p>Dropdown Component</p>)}
</div>
);
}
Find a codesandbox example here.
2021 Update:
It has bee a while since I added this response, and since it still seems to garner some interest, I thought I would update it to a more current React version. On 2021, this is how I would write this component:
import React, { useState } from "react";
import "./DropDown.css";
export function DropDown({ options, callback }) {
const [selected, setSelected] = useState("");
const [expanded, setExpanded] = useState(false);
function expand() {
setExpanded(true);
}
function close() {
setExpanded(false);
}
function select(event) {
const value = event.target.textContent;
callback(value);
close();
setSelected(value);
}
return (
<div className="dropdown" tabIndex={0} onFocus={expand} onBlur={close} >
<div>{selected}</div>
{expanded ? (
<div className={"dropdown-options-list"}>
{options.map((O) => (
<div className={"dropdown-option"} onClick={select}>
{O}
</div>
))}
</div>
) : null}
</div>
);
}
Original Answer (2016):
Here is the solution that best worked for me without attaching events to the container:
Certain HTML elements can have what is known as "focus", for example input elements. Those elements will also respond to the blur event, when they lose that focus.
To give any element the capacity to have focus, just make sure its tabindex attribute is set to anything other than -1. In regular HTML that would be by setting the tabindex attribute, but in React you have to use tabIndex (note the capital I).
You can also do it via JavaScript with element.setAttribute('tabindex',0)
This is what I was using it for, to make a custom DropDown menu.
var DropDownMenu = React.createClass({
getInitialState: function(){
return {
expanded: false
}
},
expand: function(){
this.setState({expanded: true});
},
collapse: function(){
this.setState({expanded: false});
},
render: function(){
if(this.state.expanded){
var dropdown = ...; //the dropdown content
} else {
var dropdown = undefined;
}
return (
<div className="dropDownMenu" tabIndex="0" onBlur={ this.collapse } >
<div className="currentValue" onClick={this.expand}>
{this.props.displayValue}
</div>
{dropdown}
</div>
);
}
});
After trying many methods here, I decided to use github.com/Pomax/react-onclickoutside because of how complete it is.
I installed the module via npm and imported it into my component:
import onClickOutside from 'react-onclickoutside'
Then, in my component class I defined the handleClickOutside method:
handleClickOutside = () => {
console.log('onClickOutside() method called')
}
And when exporting my component I wrapped it in onClickOutside():
export default onClickOutside(NameOfComponent)
That's it.
Hook implementation based on Tanner Linsley's excellent talk at JSConf Hawaii 2020:
useOuterClick API
const Client = () => {
const innerRef = useOuterClick(ev => {/*event handler code on outer click*/});
return <div ref={innerRef}> Inside </div>
};
Implementation
function useOuterClick(callback) {
const callbackRef = useRef(); // initialize mutable ref, which stores callback
const innerRef = useRef(); // returned to client, who marks "border" element
// update cb on each render, so second useEffect has access to current value
useEffect(() => { callbackRef.current = callback; });
useEffect(() => {
document.addEventListener("click", handleClick);
return () => document.removeEventListener("click", handleClick);
function handleClick(e) {
if (innerRef.current && callbackRef.current &&
!innerRef.current.contains(e.target)
) callbackRef.current(e);
}
}, []); // no dependencies -> stable click listener
return innerRef; // convenience for client (doesn't need to init ref himself)
}
Here is a working example:
/*
Custom Hook
*/
function useOuterClick(callback) {
const innerRef = useRef();
const callbackRef = useRef();
// set current callback in ref, before second useEffect uses it
useEffect(() => { // useEffect wrapper to be safe for concurrent mode
callbackRef.current = callback;
});
useEffect(() => {
document.addEventListener("click", handleClick);
return () => document.removeEventListener("click", handleClick);
// read most recent callback and innerRef dom node from refs
function handleClick(e) {
if (
innerRef.current &&
callbackRef.current &&
!innerRef.current.contains(e.target)
) {
callbackRef.current(e);
}
}
}, []); // no need for callback + innerRef dep
return innerRef; // return ref; client can omit `useRef`
}
/*
Usage
*/
const Client = () => {
const [counter, setCounter] = useState(0);
const innerRef = useOuterClick(e => {
// counter state is up-to-date, when handler is called
alert(`Clicked outside! Increment counter to ${counter + 1}`);
setCounter(c => c + 1);
});
return (
<div>
<p>Click outside!</p>
<div id="container" ref={innerRef}>
Inside, counter: {counter}
</div>
</div>
);
};
ReactDOM.render(<Client />, document.getElementById("root"));
#container { border: 1px solid red; padding: 20px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js" integrity="sha256-Ef0vObdWpkMAnxp39TYSLVS/vVUokDE8CDFnx7tjY6U=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js" integrity="sha256-p2yuFdE8hNZsQ31Qk+s8N+Me2fL5cc6NKXOC0U9uGww=" crossorigin="anonymous"></script>
<script> var {useRef, useEffect, useCallback, useState} = React</script>
<div id="root"></div>
Key points
useOuterClick makes use of mutable refs to provide lean Client API
stable click listener for lifetime of containing component ([] deps)
Client can set callback without needing to memoize it by useCallback
callback body has access to the most recent props and state - no stale closure values
(Side note for iOS)
iOS in general treats only certain elements as clickable. To make outer clicks work, choose a different click listener than document - nothing upwards including body. E.g. add a listener on the React root div and expand its height, like height: 100vh, to catch all outside clicks. Source: quirksmode.org
[Update] Solution with React ^16.8 using Hooks
CodeSandbox
import React, { useEffect, useRef, useState } from 'react';
const SampleComponent = () => {
const [clickedOutside, setClickedOutside] = useState(false);
const myRef = useRef();
const handleClickOutside = e => {
if (!myRef.current.contains(e.target)) {
setClickedOutside(true);
}
};
const handleClickInside = () => setClickedOutside(false);
useEffect(() => {
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
});
return (
<button ref={myRef} onClick={handleClickInside}>
{clickedOutside ? 'Bye!' : 'Hello!'}
</button>
);
};
export default SampleComponent;
Solution with React ^16.3:
CodeSandbox
import React, { Component } from "react";
class SampleComponent extends Component {
state = {
clickedOutside: false
};
componentDidMount() {
document.addEventListener("mousedown", this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClickOutside);
}
myRef = React.createRef();
handleClickOutside = e => {
if (!this.myRef.current.contains(e.target)) {
this.setState({ clickedOutside: true });
}
};
handleClickInside = () => this.setState({ clickedOutside: false });
render() {
return (
<button ref={this.myRef} onClick={this.handleClickInside}>
{this.state.clickedOutside ? "Bye!" : "Hello!"}
</button>
);
}
}
export default SampleComponent;
None of the other answers here worked for me. I was trying to hide a popup on blur, but since the contents were absolutely positioned, the onBlur was firing even on the click of inner contents too.
Here is an approach that did work for me:
// Inside the component:
onBlur(event) {
// currentTarget refers to this component.
// relatedTarget refers to the element where the user clicked (or focused) which
// triggered this event.
// So in effect, this condition checks if the user clicked outside the component.
if (!event.currentTarget.contains(event.relatedTarget)) {
// do your thing.
}
},
Hope this helps.
I found a solution thanks to Ben Alpert on discuss.reactjs.org. The suggested approach attaches a handler to the document but that turned out to be problematic. Clicking on one of the components in my tree resulted in a rerender which removed the clicked element on update. Because the rerender from React happens before the document body handler is called, the element was not detected as "inside" the tree.
The solution to this was to add the handler on the application root element.
main:
window.__myapp_container = document.getElementById('app')
React.render(<App/>, window.__myapp_container)
component:
import { Component, PropTypes } from 'react';
import ReactDOM from 'react-dom';
export default class ClickListener extends Component {
static propTypes = {
children: PropTypes.node.isRequired,
onClickOutside: PropTypes.func.isRequired
}
componentDidMount () {
window.__myapp_container.addEventListener('click', this.handleDocumentClick)
}
componentWillUnmount () {
window.__myapp_container.removeEventListener('click', this.handleDocumentClick)
}
/* using fat arrow to bind to instance */
handleDocumentClick = (evt) => {
const area = ReactDOM.findDOMNode(this.refs.area);
if (!area.contains(evt.target)) {
this.props.onClickOutside(evt)
}
}
render () {
return (
<div ref='area'>
{this.props.children}
</div>
)
}
}
MUI has a small component to solve this problem: https://mui.com/base/react-click-away-listener/ that you can cherry-pick it. It weights below 1 kB gzipped, it supports mobile, IE 11, and portals.
The Ez way... (UPDATED 2022)
Create a hook: useOutsideClick.ts
export function useOutsideClick(ref: any, onClickOut: () => void){
useEffect(() => {
const onClick = ({target}: any) => !ref.contains(target) && onClickOut?.()
document.addEventListener("click", onClick);
return () => document.removeEventListener("click", onClick);
}, []);
}
Add componentRef to your component and call useOutsideClick
export function Example(){
const componentRef = useRef();
useOutsideClick(componentRef.current!, () => {
// do something here
});
return (
<div ref={componentRef as any}> My Component </div>
)
}
Alternatively:
const onClickOutsideListener = () => {
alert("click outside")
document.removeEventListener("click", onClickOutsideListener)
}
...
return (
<div
onMouseLeave={() => {
document.addEventListener("click", onClickOutsideListener)
}}
>
...
</div>
with typescript
function Tooltip(): ReactElement {
const [show, setShow] = useState(false);
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
function handleClickOutside(event: MouseEvent): void {
if (ref.current && !ref.current.contains(event.target as Node)) {
setShow(false);
}
}
// Bind the event listener
document.addEventListener('mousedown', handleClickOutside);
return () => {
// Unbind the event listener on clean up
document.removeEventListener('mousedown', handleClickOutside);
};
});
return (
<div ref={ref}></div>
)
}
import { useClickAway } from "react-use";
useClickAway(ref, () => console.log('OUTSIDE CLICKED'));
For those who need absolute positioning, a simple option I opted for is to add a wrapper component that is styled to cover the whole page with a transparent background. Then you can add an onClick on this element to close your inside component.
<div style={{
position: 'fixed',
top: '0', right: '0', bottom: '0', left: '0',
zIndex: '1000',
}} onClick={() => handleOutsideClick()} >
<Content style={{position: 'absolute'}}/>
</div>
As it is right now if you add a click handler on content, the event will also be propagated to the upper div and therefore trigger the handlerOutsideClick. If this is not your desired behavior, simply stop the event progation on your handler.
<Content style={{position: 'absolute'}} onClick={e => {
e.stopPropagation();
desiredFunctionCall();
}}/>
`
Here is my approach (demo - https://jsfiddle.net/agymay93/4/):
I've created special component called WatchClickOutside and it can be used like (I assume JSX syntax):
<WatchClickOutside onClickOutside={this.handleClose}>
<SomeDropdownEtc>
</WatchClickOutside>
Here is code of WatchClickOutside component:
import React, { Component } from 'react';
export default class WatchClickOutside extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
componentWillMount() {
document.body.addEventListener('click', this.handleClick);
}
componentWillUnmount() {
// remember to remove all events to avoid memory leaks
document.body.removeEventListener('click', this.handleClick);
}
handleClick(event) {
const {container} = this.refs; // get container that we'll wait to be clicked outside
const {onClickOutside} = this.props; // get click outside callback
const {target} = event; // get direct click event target
// if there is no proper callback - no point of checking
if (typeof onClickOutside !== 'function') {
return;
}
// if target is container - container was not clicked outside
// if container contains clicked target - click was not outside of it
if (target !== container && !container.contains(target)) {
onClickOutside(event); // clicked outside - fire callback
}
}
render() {
return (
<div ref="container">
{this.props.children}
</div>
);
}
}
This already has many answers but they don't address e.stopPropagation() and preventing clicking on react links outside of the element you wish to close.
Due to the fact that React has it's own artificial event handler you aren't able to use document as the base for event listeners. You need to e.stopPropagation() before this as React uses document itself. If you use for example document.querySelector('body') instead. You are able to prevent the click from the React link. Following is an example of how I implement click outside and close.
This uses ES6 and React 16.3.
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
isOpen: false,
};
this.insideContainer = React.createRef();
}
componentWillMount() {
document.querySelector('body').addEventListener("click", this.handleClick, false);
}
componentWillUnmount() {
document.querySelector('body').removeEventListener("click", this.handleClick, false);
}
handleClick(e) {
/* Check that we've clicked outside of the container and that it is open */
if (!this.insideContainer.current.contains(e.target) && this.state.isOpen === true) {
e.preventDefault();
e.stopPropagation();
this.setState({
isOpen: false,
})
}
};
togggleOpenHandler(e) {
e.preventDefault();
this.setState({
isOpen: !this.state.isOpen,
})
}
render(){
return(
<div>
<span ref={this.insideContainer}>
<a href="#open-container" onClick={(e) => this.togggleOpenHandler(e)}>Open me</a>
</span>
<a href="/" onClick({/* clickHandler */})>
Will not trigger a click when inside is open.
</a>
</div>
);
}
}
export default App;
Typescript with Hooks
Note: I'm using React version 16.3, with React.createRef. For other versions use the ref callback.
Dropdown component:
interface DropdownProps {
...
};
export const Dropdown: React.FC<DropdownProps> () {
const ref: React.RefObject<HTMLDivElement> = React.createRef();
const handleClickOutside = (event: MouseEvent) => {
if (ref && ref !== null) {
const cur = ref.current;
if (cur && !cur.contains(event.target as Node)) {
// close all dropdowns
}
}
}
useEffect(() => {
// Bind the event listener
document.addEventListener("mousedown", handleClickOutside);
return () => {
// Unbind the event listener on clean up
document.removeEventListener("mousedown", handleClickOutside);
};
});
return (
<div ref={ref}>
...
</div>
);
}
I did this partly by following this and by following the React official docs on handling refs which requires react ^16.3. This is the only thing that worked for me after trying some of the other suggestions here...
class App extends Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
componentWillMount() {
document.addEventListener("mousedown", this.handleClick, false);
}
componentWillUnmount() {
document.removeEventListener("mousedown", this.handleClick, false);
}
handleClick = e => {
/*Validating click is made inside a component*/
if ( this.inputRef.current === e.target ) {
return;
}
this.handleclickOutside();
};
handleClickOutside(){
/*code to handle what to do when clicked outside*/
}
render(){
return(
<div>
<span ref={this.inputRef} />
</div>
)
}
}
Simply with ClickAwayListener from mui (material-ui):
<ClickAwayListener onClickAway={handleClickAway}>
{children}
<ClickAwayListener >
for more info you can check:https://mui.com/base/react-click-away-listener/
To extend on the accepted answer made by Ben Bud, if you are using styled-components, passing refs that way will give you an error such as "this.wrapperRef.contains is not a function".
The suggested fix, in the comments, to wrap the styled component with a div and pass the ref there, works.
Having said that, in their docs they already explain the reason for this and the proper use of refs within styled-components:
Passing a ref prop to a styled component will give you an instance of the StyledComponent wrapper, but not to the underlying DOM node. This is due to how refs work. It's not possible to call DOM methods, like focus, on our wrappers directly.
To get a ref to the actual, wrapped DOM node, pass the callback to the innerRef prop instead.
Like so:
<StyledDiv innerRef={el => { this.el = el }} />
Then you can access it directly within the "handleClickOutside" function:
handleClickOutside = e => {
if (this.el && !this.el.contains(e.target)) {
console.log('clicked outside')
}
}
This also applies for the "onBlur" approach:
componentDidMount(){
this.el.focus()
}
blurHandler = () => {
console.log('clicked outside')
}
render(){
return(
<StyledDiv
onBlur={this.blurHandler}
tabIndex="0"
innerRef={el => { this.el = el }}
/>
)
}
This is my way of solving the problem
I return a boolean value from my custom hook, and when this value changes (true if the click was outside of the ref that I passed as an arg), this way i can catch this change with an useEffect hook, i hope it's clear for you.
Here's a live example:
Live Example on codesandbox
import { useEffect, useRef, useState } from "react";
const useOutsideClick = (ref) => {
const [outsieClick, setOutsideClick] = useState(null);
useEffect(() => {
const handleClickOutside = (e) => {
if (!ref.current.contains(e.target)) {
setOutsideClick(true);
} else {
setOutsideClick(false);
}
setOutsideClick(null);
};
document.addEventListener("mousedown", handleClickOutside);
return () => {
document.removeEventListener("mousedown", handleClickOutside);
};
}, [ref]);
return outsieClick;
};
export const App = () => {
const buttonRef = useRef(null);
const buttonClickedOutside = useOutsideClick(buttonRef);
useEffect(() => {
// if the the click was outside of the button
// do whatever you want
if (buttonClickedOutside) {
alert("hey you clicked outside of the button");
}
}, [buttonClickedOutside]);
return (
<div className="App">
<button ref={buttonRef}>click outside me</button>
</div>
);
}
Typescript + simplified version of #ford04's proposal:
useOuterClick API
const Client = () => {
const ref = useOuterClick<HTMLDivElement>(e => { /* Custom-event-handler */ });
return <div ref={ref}> Inside </div>
};
Implementation
export default function useOuterClick<T extends HTMLElement>(callback: Function) {
const callbackRef = useRef<Function>(); // initialize mutable ref, which stores callback
const innerRef = useRef<T>(null); // returned to client, who marks "border" element
// update cb on each render, so second useEffect has access to current value
useEffect(() => { callbackRef.current = callback; });
useEffect(() => {
document.addEventListener("click", _onClick);
return () => document.removeEventListener("click", _onClick);
function _onClick(e: any): void {
const clickedOutside = !(innerRef.current?.contains(e.target));
if (clickedOutside)
callbackRef.current?.(e);
}
}, []); // no dependencies -> stable click listener
return innerRef; // convenience for client (doesn't need to init ref himself)
}
So I faced a similar problem but in my case the selected answer here wasn't working because I had a button for the dropdown which is, well, a part of the document. So clicking the button also triggered the handleClickOutside function. To stop that from triggering, I had to add a new ref to the button and this !menuBtnRef.current.contains(e.target) to the conditional. I'm leaving it here if someone is facing the same issue like me.
Here's how the component looks like now:
const Component = () => {
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
const menuRef = useRef(null);
const menuBtnRef = useRef(null);
const handleDropdown = (e) => {
setIsDropdownOpen(!isDropdownOpen);
}
const handleClickOutside = (e) => {
if (menuRef.current && !menuRef.current.contains(e.target) && !menuBtnRef.current.contains(e.target)) {
setIsDropdownOpen(false);
}
}
useEffect(() => {
document.addEventListener('mousedown', handleClickOutside, true);
return () => {
document.removeEventListener('mousedown', handleClickOutside, true);
};
}, []);
return (
<button ref={menuBtnRef} onClick={handleDropdown}></button>
<div ref={menuRef} className={`${isDropdownOpen ? styles.dropdownMenuOpen : ''}`}>
// ...dropdown items
</div>
)
}
My biggest concern with all of the other answers is having to filter click events from the root/parent down. I found the easiest way was to simply set a sibling element with position: fixed, a z-index 1 behind the dropdown and handle the click event on the fixed element inside the same component. Keeps everything centralized to a given component.
Example code
#HTML
<div className="parent">
<div className={`dropdown ${this.state.open ? open : ''}`}>
...content
</div>
<div className="outer-handler" onClick={() => this.setState({open: false})}>
</div>
</div>
#SASS
.dropdown {
display: none;
position: absolute;
top: 0px;
left: 0px;
z-index: 100;
&.open {
display: block;
}
}
.outer-handler {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
opacity: 0;
z-index: 99;
display: none;
&.open {
display: block;
}
}
componentWillMount(){
document.addEventListener('mousedown', this.handleClickOutside)
}
handleClickOutside(event) {
if(event.path[0].id !== 'your-button'){
this.setState({showWhatever: false})
}
}
Event path[0] is the last item clicked
I used this module (I have no association with the author)
npm install react-onclickout --save
const ClickOutHandler = require('react-onclickout');
class ExampleComponent extends React.Component {
onClickOut(e) {
if (hasClass(e.target, 'ignore-me')) return;
alert('user clicked outside of the component!');
}
render() {
return (
<ClickOutHandler onClickOut={this.onClickOut}>
<div>Click outside of me!</div>
</ClickOutHandler>
);
}
}
It did the job nicely.
UseOnClickOutside Hook - React 16.8 +
Create a general useOnOutsideClick function
export const useOnOutsideClick = handleOutsideClick => {
const innerBorderRef = useRef();
const onClick = event => {
if (
innerBorderRef.current &&
!innerBorderRef.current.contains(event.target)
) {
handleOutsideClick();
}
};
useMountEffect(() => {
document.addEventListener("click", onClick, true);
return () => {
document.removeEventListener("click", onClick, true);
};
});
return { innerBorderRef };
};
const useMountEffect = fun => useEffect(fun, []);
Then use the hook in any functional component.
const OutsideClickDemo = ({ currentMode, changeContactAppMode }) => {
const [open, setOpen] = useState(false);
const { innerBorderRef } = useOnOutsideClick(() => setOpen(false));
return (
<div>
<button onClick={() => setOpen(true)}>open</button>
{open && (
<div ref={innerBorderRef}>
<SomeChild/>
</div>
)}
</div>
);
};
Link to demo
Partially inspired by #pau1fitzgerald answer.
In my DROPDOWN case the Ben Bud's solution worked well, but I had a separate toggle button with an onClick handler. So the outside clicking logic conflicted with the button onClick toggler. Here is how I solved it by passing the button's ref as well:
import React, { useRef, useEffect, useState } from "react";
/**
* Hook that triggers onClose when clicked outside of ref and buttonRef elements
*/
function useOutsideClicker(ref, buttonRef, onOutsideClick) {
useEffect(() => {
function handleClickOutside(event) {
/* clicked on the element itself */
if (ref.current && !ref.current.contains(event.target)) {
return;
}
/* clicked on the toggle button */
if (buttonRef.current && !buttonRef.current.contains(event.target)) {
return;
}
/* If it's something else, trigger onClose */
onOutsideClick();
}
// Bind the event listener
document.addEventListener("mousedown", handleClickOutside);
return () => {
// Unbind the event listener on clean up
document.removeEventListener("mousedown", handleClickOutside);
};
}, [ref]);
}
/**
* Component that alerts if you click outside of it
*/
export default function DropdownMenu(props) {
const wrapperRef = useRef(null);
const buttonRef = useRef(null);
const [dropdownVisible, setDropdownVisible] = useState(false);
useOutsideClicker(wrapperRef, buttonRef, closeDropdown);
const toggleDropdown = () => setDropdownVisible(visible => !visible);
const closeDropdown = () => setDropdownVisible(false);
return (
<div>
<button onClick={toggleDropdown} ref={buttonRef}>Dropdown Toggler</button>
{dropdownVisible && <div ref={wrapperRef}>{props.children}</div>}
</div>
);
}
I had a similar use case where I had to develop a custom dropdown menu. it should close automatically when the user clicks outside. here is the recent React Hooks implementation-
import { useEffect, useRef, useState } from "react";
export const App = () => {
const ref = useRef();
const [isMenuOpen, setIsMenuOpen] = useState(false);
useEffect(() => {
const checkIfClickedOutside = (e) => {
// If the menu is open and the clicked target is not within the menu,
// then close the menu
if (isMenuOpen && ref.current && !ref.current.contains(e.target)) {
setIsMenuOpen(false);
}
};
document.addEventListener("mousedown", checkIfClickedOutside);
return () => {
// Cleanup the event listener
document.removeEventListener("mousedown", checkIfClickedOutside);
};
}, [isMenuOpen]);
return (
<div className="wrapper" ref={ref}>
<button
className="button"
onClick={() => setIsMenuOpen((oldState) => !oldState)}
>
Click Me
</button>
{isMenuOpen && (
<ul className="list">
<li className="list-item">dropdown option 1</li>
<li className="list-item">dropdown option 2</li>
<li className="list-item">dropdown option 3</li>
<li className="list-item">dropdown option 4</li>
</ul>
)}
</div>
);
}
An example with Strategy
I like the provided solutions that use to do the same thing by creating a wrapper around the component.
Since this is more of a behavior I thought of Strategy and came up with the following.
I'm new with React and I need a bit of help in order to save some boilerplate in the use cases
Please review and tell me what you think.
ClickOutsideBehavior
import ReactDOM from 'react-dom';
export default class ClickOutsideBehavior {
constructor({component, appContainer, onClickOutside}) {
// Can I extend the passed component's lifecycle events from here?
this.component = component;
this.appContainer = appContainer;
this.onClickOutside = onClickOutside;
}
enable() {
this.appContainer.addEventListener('click', this.handleDocumentClick);
}
disable() {
this.appContainer.removeEventListener('click', this.handleDocumentClick);
}
handleDocumentClick = (event) => {
const area = ReactDOM.findDOMNode(this.component);
if (!area.contains(event.target)) {
this.onClickOutside(event)
}
}
}
Sample Usage
import React, {Component} from 'react';
import {APP_CONTAINER} from '../const';
import ClickOutsideBehavior from '../ClickOutsideBehavior';
export default class AddCardControl extends Component {
constructor() {
super();
this.state = {
toggledOn: false,
text: ''
};
this.clickOutsideStrategy = new ClickOutsideBehavior({
component: this,
appContainer: APP_CONTAINER,
onClickOutside: () => this.toggleState(false)
});
}
componentDidMount () {
this.setState({toggledOn: !!this.props.toggledOn});
this.clickOutsideStrategy.enable();
}
componentWillUnmount () {
this.clickOutsideStrategy.disable();
}
toggleState(isOn) {
this.setState({toggledOn: isOn});
}
render() {...}
}
Notes
I thought of storing the passed component lifecycle hooks and override them with methods simillar to this:
const baseDidMount = component.componentDidMount;
component.componentDidMount = () => {
this.enable();
baseDidMount.call(component)
}
component is the component passed to the constructor of ClickOutsideBehavior.
This will remove the enable/disable boilerplate from the user of this behavior but it doesn't look very nice though

Categories