Skip to content

Commit

Permalink
fix: handling click outside on Forms.Select
Browse files Browse the repository at this point in the history
Signed-off-by: Antonio Sonis <[email protected]>
  • Loading branch information
tonysnowboardunderthebridge committed Nov 8, 2024
1 parent d920e50 commit dc0350d
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
28 changes: 25 additions & 3 deletions src/components/forms/Select.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,10 @@ function Select ({
backgroundColor = WHITE,
inputTextClassName = '',
beforeIcon = {},
paddingClass = ''
paddingClass = '',
handleClickOutside = false
}) {
const wrapperRef = useRef(null)
const inputRef = useRef()
const [showOptions, setShowOptions] = useState(false)
// eslint-disable-next-line no-unused-vars
Expand Down Expand Up @@ -105,6 +107,22 @@ function Select ({
}
}, [value])

useEffect(() => {
if (showOptions && handleClickOutside) {
function innerHandleClickOutside (event) {
if (wrapperRef.current && !wrapperRef.current.contains(event.target)) {
setShowOptions(false)
}
}
// Bind the event listener
document.addEventListener('mousedown', innerHandleClickOutside)
return () => {
// Unbind the event listener on clean up
document.removeEventListener('mousedown', innerHandleClickOutside)
}
}
}, [handleClickOutside, showOptions])

useEffect(() => {
if (disabled) {
const className = normalClassName() + ' ' + commonStyles['apply-opacity-30']
Expand Down Expand Up @@ -170,7 +188,7 @@ function Select ({
}

return (
<div className={containerClassName} {...dataProps}>
<div className={containerClassName} {...dataProps} ref={wrapperRef}>
<div className={wrapperClassName}>
{beforeIcon?.iconName && getBeforeIcon()}
<input type='text' name={name} value={value} className={inputClassName} ref={inputRef} disabled={disabled} placeholder={placeholder} onFocus={() => handleFocus()} onBlur={(e) => handleBlur(e)} readOnly />
Expand Down Expand Up @@ -285,7 +303,11 @@ Select.propTypes = {
/**
* paddingClass
*/
paddingClass: PropTypes.string
paddingClass: PropTypes.string,
/**
* handleClickOutside
*/
handleClickOutside: PropTypes.bool
}

export default Select
3 changes: 2 additions & 1 deletion src/stories/forms/Select.stories.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -198,5 +198,6 @@ WithBeforeIcon.args = {
iconName: 'AddIcon',
color: ERROR_RED,
size: LARGE
}
},
handleClickOutside: true
}

0 comments on commit dc0350d

Please sign in to comment.