skip to Main Content

I wanted to test out the following code snippet in the browsers console:

const dropdown = document.querySelector('w-48');

const handleClick = (event) => {
  if (dropdown.contains(event.target)) {
    console.log('Inside dropdown');
  } else {
    console.log('OUTSIDE Dropdown');
  }
}

document.addEventListener('click', handleClick, true);

The component for the Dropdown itself looks like so:

import { useState } from "react";
import { GoChevronDown, GoChevronLeft } from "react-icons/go";
import Panel from "./Panel";

function Dropdown({ options, value, onChange }) {
  const [isOpen, setIsOpen] = useState(false);

  const handleClick = () => {
    setIsOpen(!isOpen);
  };

  const handleOptionClick = (option) => {
    // CLOSE DROPDOWN
    setIsOpen(false);
    // WHAT OPTION DID THE USER CLICK ON??
    onChange(option);
  };

  const renderedOptions = options.map((option) => {
    return (
      <div
        className='hover:g-sky-100 rounded cursor-pointer p-1'
        onClick={() => handleOptionClick(option)}
        key={option.value}
      >
        {option.label}
      </div>
    );
  });

  return (
    <div className='w-48 relative'>
      <Panel
        className='flex justify-between items-center cursor-pointer'
        onClick={handleClick}
      >
        {value?.label || "Select..."}
        {isOpen ? (
          <GoChevronDown className='text-3xl' />
        ) : (
          <GoChevronLeft className='text-3xl' />
        )}
      </Panel>
      {isOpen && <Panel className='absolute top-full'>{renderedOptions}</Panel>}
    </div>
  );
}

export default Dropdown;

But as soon as I tried to open the dropdown, I got the following error:

Cannot read properties of null (reading ‘contains’) TypeError: Cannot
read properties of null (reading ‘contains’)
at HTMLDocument.handleClick (:4:16)

My expectation was to see a console log of inside dropdown.

2

Answers


  1. wrap your class variable in iffi like this and then use it

    let dropdown
    
    (() => {
     dropdown = document.querySelector('.w-48');
    })()
    

    also one highlight in your code you are missing (".") in front of class in querySelector classes should be accessed with (".") and ids with ("#")
    in querySelector

    here we are using iffi as iffi’s are immediately invoked function’s which loads before the browser’s first paint on screen.

    Login or Signup to reply.
  2. Place . in front of w-48 and put ? in front of .contains(event.target).

    const dropdown = document.querySelector('.w-48');
    
    const handleClick = (event) => {
      if (dropdown?.contains(event.target)) {
        console.log('Inside dropdown');
      } else {
        console.log('OUTSIDE Dropdown');
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search