{"size": 2152, "ext": "js", "max_stars_repo_path": "src/components/Dropdown.js", "max_stars_repo_name": "edujtm/edujtm.github.io", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/components/Dropdown.js", "max_issues_repo_name": "edujtm/edujtm.github.io", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/components/Dropdown.js", "max_forks_repo_name": "edujtm/edujtm.github.io", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 24.1797752809, "max_line_length": 76, "alphanum_fraction": 0.4781598513}
import React, { useState, useEffect, useContext } from 'react';
import classNames from 'classnames';

import { ThemeContext } from './ThemeProvider';

import * as dropdownStyles from "../styles/components/Dropdown.module.scss";

const Dropdown = ({ title, items, action }) => {
  const [menuDisplayed, setDisplay] = useState(false);
  const { isDarkMode } = useContext(ThemeContext);

  const hideDropdownMenu = () => {
    setDisplay(false)
  }

  const showDropdownMenu = (event) => {
    event.preventDefault();
    setDisplay(true);
  }

  useEffect(() => {
    if (menuDisplayed) {
      document.addEventListener('click', hideDropdownMenu);
      return () => { 
        document.removeEventListener('click', hideDropdownMenu) 
      };
    } 
  }, [menuDisplayed])

  const dropdownClass = classNames({
    [dropdownStyles.dropdown]: true,
    [dropdownStyles.darkTheme]: isDarkMode
  });

  const buttonClass = classNames({
    [dropdownStyles.button]: true,
    [dropdownStyles.darkTheme]: isDarkMode
  });

  return (
    <div className={dropdownClass}>
      <div 
        role="button"
        tabindex="0"
        className={buttonClass} 
        onClick={showDropdownMenu}
        onKeyDown={(ev) => {
          if (ev.keyCode === 40) {
            showDropdownMenu(ev);
          }
        }}
      >
        {title}
      </div>
      { menuDisplayed ? (
        <ul>
          {items.map((item) => {
            return ( 
              <li key={item.id}>
                <div 
                  role="button" 
                  tabindex="0"
                  onKeyDown={(ev) => {
                    if (ev.keyCode === 13) {
                      action(item.id);
                    }
                  }}
                  onClick={() => action(item.id)}
                >
                  <button 
                    href="#" 
                    onClick={(e) => e.preventDefault()}
                  >
                      {item.name}
                  </button>
                </div>
              </li> 
            );
          })}
        </ul>
      ) : (
        null
      )}
    </div>
  );
}

export default Dropdown;
