hide reacts when clicked outside

This commit is contained in:
mrfry 2021-03-09 15:22:17 +01:00
parent f749ce1279
commit 275ebc749a
2 changed files with 31 additions and 13 deletions

View file

@ -207,16 +207,15 @@ export default function Comments({
) : null} ) : null}
</Modal> </Modal>
) : null} ) : null}
<div <div className={'actions'}>
className={'actions'} <span
onClick={() => { onClick={() => {
setCommentsShowing(true) setCommentsShowing(true)
if (commentCount === 0) { if (commentCount === 0) {
setAddingNewComment(true) setAddingNewComment(true)
} }
}} }}
> >
<span>
{commentCount === 0 {commentCount === 0
? 'New comment' ? 'New comment'
: `Show ${commentCount} comment${commentCount > 1 ? 's' : ''}`} : `Show ${commentCount} comment${commentCount > 1 ? 's' : ''}`}

View file

@ -1,10 +1,25 @@
import React, { useState } from 'react' import React, { useState, useEffect, useRef } from 'react'
import Tooltip from './tooltip.js' import Tooltip from './tooltip.js'
import styles from './reactButton.module.css' import styles from './reactButton.module.css'
import reactions from '../data/reactions.json' import reactions from '../data/reactions.json'
function useOutsideAlerter(ref, action) {
useEffect(() => {
function handleClickOutside(event) {
if (ref.current && !ref.current.contains(event.target)) {
action()
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => {
document.removeEventListener('mousedown', handleClickOutside)
}
}, [ref])
}
function ExistingReacts({ existingReacts, onClick, uid }) { function ExistingReacts({ existingReacts, onClick, uid }) {
return ( return (
<div className={styles.reactionContainer}> <div className={styles.reactionContainer}>
@ -69,6 +84,10 @@ function RenderEmojis({ onClick }) {
export default function ReactButton({ onClick, existingReacts, uid }) { export default function ReactButton({ onClick, existingReacts, uid }) {
const [opened, setOpened] = useState(false) const [opened, setOpened] = useState(false)
const wrapperRef = useRef(null)
useOutsideAlerter(wrapperRef, () => {
setOpened(false)
})
return ( return (
<div <div
@ -77,7 +96,7 @@ export default function ReactButton({ onClick, existingReacts, uid }) {
setOpened(true) setOpened(true)
}} }}
onMouseLeave={() => { onMouseLeave={() => {
setOpened(false) // setOpened(false)
}} }}
> >
<Tooltip <Tooltip
@ -93,7 +112,7 @@ export default function ReactButton({ onClick, existingReacts, uid }) {
/> />
)} )}
> >
<div className={styles.reactionContainer}> <div ref={wrapperRef} className={styles.reactionContainer}>
<RenderEmojis <RenderEmojis
onClick={(e) => { onClick={(e) => {
// setOpened(false) // setOpened(false)