I have been delving into learning React by challenging myself with a React problem. The code challenge I'm facing involves trying to close a drop-down when clicking outside of it. Despite my efforts to debug, I haven't had much luck in solving this issue.
Can anyone provide insights or comments on the code toolbar? Understanding the video explaining each functionality has proven difficult for me. Additionally, I've looked up information on spread and useRef but am unsure why spread is being used in this particular instance.
After further searching without success, I am feeling stuck on how to resolve this problem. Below is the code I have written along with a StackBlitz link. Any assistance you can offer would be greatly appreciated.
import { useEffect, useRef, useState } from 'react';
import './stateDropdown.css';
import { states } from './States';
export function StateDropdown() {
const [isDropDownDisplayed, setIsDropdowndisplayed] = useState(false);
const [selectedStates, setSelectedStates] = useState<Record<string, boolean>>(
states.reduce((obj, state) => ({ ...obj, [state.abbreviation]: false }), {})
);
const numberOfStatesSelected =
Object.values(selectedStates).filter(Boolean).length;
const dropDownRef = useRef(null);
useEffect(() => {
const onClick = (e: any) => {
if (e.target !== dropDownRef.current) {
console.log('we are here');
setIsDropdowndisplayed(false);
}
};
document.addEventListener('click', () => {});
// clean up
return () => {
document.removeEventListener('click', onClick);
};
}, []);
return (
<fieldset className="state-dropdown">
<button
className=""
onClick={(e) => {
e.stopPropagation();
setIsDropdowndisplayed((prevState) => !prevState);
}}
>
{numberOfStatesSelected > 0
? `${numberOfStatesSelected} states selected`
: '-- Select your states --'}
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke-width="1.5"
stroke="currentColor"
className="w-6 h-6"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M6 13.5V3.75m0 9.75a1.5 1.5 0 010 3m0-3a1.5 1.5 0 000 3m0 3.75V16.5m12-3V3.75m0 9.75a1.5 1.5 0 010 3m0-3a1.5 1.5 0 000 3m0 3.75V16.5m-6-9V3.75m0 3.75a1.5 1.5 0 010 3m0-3a1.5 1.5 0 000 3m0 9.75V10.5"
/>
</svg>
</button>
{isDropDownDisplayed && (
<div
onClick={(e) => {
e.stopPropagation();
}}
ref={dropDownRef}
className="panel"
>
{states.map((state) => (
<fieldset
key={state.abbreviation}
className={selectedStates[state.abbreviation] ? `selected` : ''}
>
<input
onChange={(e) =>
setSelectedStates({
...selectedStates,
[state.abbreviation]: e.target.checked,
})
}
checked={selectedStates[state.abbreviation]}
id={`input-${state.abbreviation}`}
type="checkbox"
/>
<label htmlFor={`input-${state.abbreviation}`}>
{state.name}
</label>
</fieldset>
))}
</div>
)}
</fieldset>
);
}