react-use#useClickAway JavaScript Examples

The following examples show how to use react-use#useClickAway. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: sidebar.jsx    From NextBook with MIT License 5 votes vote down vote up
function SideBar() {
  const { toc, projectTitle } = config
  const sideBarCtx = useContext(SideBarContext)
  const isWide = useMedia('(min-width: 770px)', false)
  const ref = useRef(null)

  useEffect(() => {
    if (isWide) {
      sideBarCtx.hideSideBar()
    }
  }, [isWide, sideBarCtx])

  useClickAway(ref, () => {
    if (!isWide) {
      sideBarCtx.hideSideBar()
    }
  })

  const sideBarStyle = sideBarCtx.sideBar
    ? 'sidebar w-2/3 z-50 h-screen bg-gray-100 dark:bg-gray-800 border-r border-gray-300 dark:border-gray-800 fixed pl-4 text-lg top-10 md:hidden'
    : 'sidebar z-50 flex-none md:w-56 xl:w-64 h-screen fixed top-10 md:top-14 hidden md:block'

  return (
    <aside className={sideBarStyle} ref={ref}>
      <div className='w-full pb-40 md:pb-16 h-full overflow-y-auto px-1'>
        <div className='flex flex-col md:mt-10'>
          <Link href='/'>
            <a aria-label={projectTitle}>
              <div className='flex flex-col items-center'>
                {process.env.NEXT_PUBLIC_USE_LOGO && (
                  <img
                    src={`/${process.env.NEXT_PUBLIC_USE_LOGO}`}
                    alt={projectTitle}
                    className='w-24 hidden md:inline-block'
                  />
                )}
                <span
                  className='hidden px-4 text-center md:inline-block font-semibold '
                  title={projectTitle}
                >
                  {projectTitle}
                </span>
              </div>
            </a>
          </Link>
          <div className='mt-6 pl-2 leading-loose tracking-wide'>
            {toc.map((toc, id) => (
              <SideBarSection toc={toc} key={id} />
            ))}
          </div>
        </div>
      </div>
    </aside>
  )
}
Example #2
Source File: LanguageSwitcher.js    From covid19india-react with MIT License 5 votes vote down vote up
function LanguageSwitcher({showLanguageSwitcher, setShowLanguageSwitcher}) {
  const {t, i18n} = useTranslation();

  const currentLanguage = Object.keys(locales).includes(i18n?.language)
    ? i18n?.language
    : i18n?.options?.fallbackLng[0];

  const transitions = useTransition(showLanguageSwitcher, {
    from: ENTER_OUT,
    enter: ENTER_IN,
    leave: ENTER_OUT,
    config: {
      mass: 1,
      tension: 100,
      friction: 15,
    },
  });

  const languageSwitcherRef = useRef();
  useClickAway(languageSwitcherRef, (e) => {
    if (e.target.className !== 'navbar-left') {
      setShowLanguageSwitcher(false);
    }
  });

  const switchLanguage = useCallback(
    (languageKey) => {
      if (i18n) i18n.changeLanguage(languageKey);
    },
    [i18n]
  );

  return transitions(
    (style, item) =>
      item && (
        <animated.div
          className="LanguageSwitcher"
          ref={languageSwitcherRef}
          {...{style}}
        >
          <h3>{t('We speak the following languages')}</h3>

          <div className="languages">
            {Object.keys(locales).map((languageKey) => (
              <div
                key={languageKey}
                className={classnames('language', {
                  'is-highlighted': currentLanguage === languageKey,
                })}
                onClick={switchLanguage.bind(this, languageKey)}
              >
                <span>{locales[languageKey]}</span>
              </div>
            ))}
          </div>

          <div
            className="close-button"
            onClick={setShowLanguageSwitcher.bind(this, false)}
          >
            <ArrowUpIcon size={16} />
          </div>
        </animated.div>
      )
  );
}
Example #3
Source File: StateDropdown.js    From covid19india-react with MIT License 4 votes vote down vote up
StateDropdown = ({stateCode, trail}) => {
  const [showDropdown, setShowDropdown] = useState(false);
  const dropdownRef = useRef();
  const history = useHistory();
  const {t} = useTranslation();

  useClickAway(dropdownRef, () => {
    setShowDropdown(false);
  });

  const transitions = useTransition(showDropdown, {
    from: {
      opacity: 0,
      transform: 'translate3d(0, 2px, 0)',
      zIndex: 999,
    },
    enter: {
      opacity: 1,
      transform: 'translate3d(0, 0px, 0)',
      zIndex: 999,
    },
    leave: {
      opacity: 0,
      transform: 'translate3d(0, 2px, 0)',
      zIndex: 999,
    },
    config: {
      mass: 1,
      tension: 210,
      friction: 20,
    },
  });

  const handleClick = useCallback(
    (stateCodeItr) => {
      setShowDropdown(false);
      history.push(`/state/${stateCodeItr}`);
    },
    [history]
  );

  return (
    <div className="StateDropdown" ref={dropdownRef}>
      <animated.h1
        className={classnames('state-name', 'fadeInUp', {
          expanded: showDropdown,
        })}
        style={trail}
        onClick={setShowDropdown.bind(this, !showDropdown)}
      >
        {t(STATE_NAMES[stateCode])}
      </animated.h1>

      {transitions(
        (style, item) =>
          item && (
            <animated.div className="dropdown" {...{style}}>
              {Object.keys(MAP_META)
                .filter(
                  (stateCodeItr) =>
                    stateCodeItr !== 'TT' && stateCodeItr !== stateCode
                )
                .sort((code1, code2) =>
                  STATE_NAMES[code1].localeCompare(STATE_NAMES[code2])
                )
                .map((stateCodeItr) => (
                  <h1
                    key={stateCodeItr}
                    className="item"
                    onClick={handleClick.bind(this, stateCodeItr)}
                  >
                    {t(STATE_NAMES[stateCodeItr])}
                  </h1>
                ))}
            </animated.div>
          )
      )}

      {showDropdown && <div className="backdrop"></div>}
    </div>
  );
}
Example #4
Source File: Timeline.js    From covid19india-react with MIT License 4 votes vote down vote up
function Timeline({date, setDate, dates, isTimelineMode, setIsTimelineMode}) {
  const {t} = useTranslation();

  const [sliderState, setSliderState] = useState(null);
  const [play, setPlay] = useState(false);
  const [showCalendar, setShowCalendar] = useState(false);
  const timelineRef = useRef();
  const timer = useRef();

  useClickAway(timelineRef, () => {
    setShowCalendar(false);
  });

  const [sliderRef, slider] = useKeenSlider({
    initial: date === '' ? Math.max(0, dates.length - 2) : dates.indexOf(date),
    dragSpeed: (val, instance) => {
      const width = instance.details().widthOrHeight;
      return (
        val *
        (width /
          ((width / 2) * Math.tan(slideDegree * (Math.PI / 180))) /
          slidesPerView)
      );
    },
    move: (s) => {
      setSliderState(s.details());
    },
    afterChange: (s) => {
      const slide = s.details().absoluteSlide;
      if (slide === s.details().size - 1) {
        ReactDOM.unstable_batchedUpdates(() => {
          setIsTimelineMode(false);
          setShowCalendar(false);
          setDate('');
        });
      } else {
        setDate(dates[slide]);
      }
    },
    mode: 'free-snap',
    slides: dates.length,
    slidesPerView,
  });

  const [radius, setRadius] = useState(0);

  useEffect(() => {
    if (slider) setRadius(slider.details().widthOrHeight);
  }, [slider]);

  const formatSlideDate = (date) => {
    if (date === getIndiaDateISO()) return t('Today');
    else if (date === getIndiaDateYesterdayISO()) return t('Yesterday');
    return formatDate(date, 'dd MMM y');
  };

  const slideValues = useMemo(() => {
    if (!sliderState) return [];
    const values = [];
    for (let i = 0; i < sliderState.size; i++) {
      const distance = sliderState.positions[i].distance * slidesPerView;
      const rotate =
        Math.abs(distance) > wheelSize / 2 ? 180 : distance * (360 / wheelSize);
      const style = {
        transform: `rotateY(${rotate}deg) translateZ(${radius}px)`,
        WebkitTransform: `rotateY(${rotate}deg) translateZ(${radius}px)`,
      };
      const className = i === sliderState.absoluteSlide ? 'current' : '';
      const slide = sliderState.absoluteSlide + Math.round(distance);
      if (Math.abs(distance) < distanceThreshold)
        values.push({className, style, slide});
    }
    return values;
  }, [sliderState, radius]);

  useKeyPressEvent('ArrowLeft', () => {
    if (slider) slider.prev();
  });

  useKeyPressEvent('ArrowRight', () => {
    if (slider) slider.next();
  });

  useKeyPressEvent('Escape', () => {
    setPlay(false);
    if (slider) slider.moveToSlide(sliderState.size - 1);
  });

  useKeyPressEvent('Enter', () => {
    setPlay(!play);
  });

  const handleClick = (index) => {
    if (index === sliderState?.absoluteSlide) {
      setShowCalendar(!showCalendar);
    } else if (slider) {
      slider.moveToSlide(index);
    }
  };

  const timeline = {
    '2020-03-25': t('Beginning of Lockdown Phase 1'),
    '2020-04-14': t('End of Lockdown Phase 1'),
    '2020-04-15': t('Beginning of Lockdown Phase 2'),
    '2020-05-03': t('End of Lockdown Phase 2'),
    '2020-05-04': t('Beginning of Lockdown Phase 3'),
    '2020-05-17': t('End of Lockdown Phase 3'),
    '2020-05-18': t('Beginning of Lockdown Phase 4'),
    '2020-05-31': t('End of Lockdown Phase 4'),
    '2020-06-01': t('Beginning of Lockdown Phase 5'),
    '2020-11-20': '?',
  };

  useEffect(() => {
    timer.current = setInterval(() => {
      if (play && slider) {
        slider.next();
      }
    }, autoPlayDelay);
    return () => {
      clearInterval(timer.current);
    };
  }, [play, slider]);

  const handleWheel = (event) => {
    if (slider) {
      if (event.deltaX > 0) {
        slider.next();
      } else if (event.deltaX < 0) {
        slider.prev();
      }
    }
  };

  const transitions = useTransition(showCalendar, {
    from: {
      pointerEvents: 'none',
      paddingTop: 0,
      marginBottom: 0,
      height: 0,
      opacity: 0,
    },
    enter: {
      pointerEvents: 'all',
      paddingTop: 36,
      marginBottom: 400,
      opacity: 1,
    },
    leave: {
      pointerEvents: 'none',
      paddingTop: 0,
      marginBottom: 0,
      height: 0,
      opacity: 0,
    },
    config: {
      mass: 1,
      tension: 100,
      friction: 15,
    },
  });

  return (
    <div className={'Timeline'} ref={timelineRef}>
      <div className="actions timeline fadeInUp" onWheel={handleWheel}>
        <div className={'wheel-buttons'}>
          <div
            className={'wheel-button left'}
            onClick={handleClick.bind(this, 0)}
          >
            <FastForward />
          </div>
          <div
            className={classnames('wheel-button', {active: play})}
            onClick={setPlay.bind(this, !play)}
          >
            {play ? <Pause /> : <Play />}
          </div>
          <div
            className="wheel-button"
            onClick={handleClick.bind(this, dates.length - 1)}
          >
            <FastForward />
          </div>
        </div>
        <div className={'wheel'} ref={sliderRef}>
          <div className="wheel__inner">
            <div className="wheel__slides">
              {slideValues.map(({className, style, slide}) => (
                <div className={`wheel__slide`} style={style} key={slide}>
                  <h5 {...{className}} onClick={handleClick.bind(this, slide)}>
                    {formatSlideDate(dates[slide])}
                  </h5>
                  <div
                    className={classnames('calendar-icon', {
                      show: slide === sliderState?.absoluteSlide,
                    })}
                    onClick={setShowCalendar.bind(this, !showCalendar)}
                  >
                    {slide !== sliderState.size - 1 && (
                      <CalendarIcon size={12} />
                    )}
                  </div>
                </div>
              ))}
            </div>
          </div>
          {slideValues.map(
            ({slide}) =>
              Object.keys(timeline).includes(dates[slide]) && (
                <h5
                  className={classnames('highlight', {
                    current: slide === sliderState?.absoluteSlide,
                  })}
                  key={slide}
                >
                  {timeline[dates[slide]]}
                </h5>
              )
          )}
        </div>
      </div>
      <Suspense fallback={<div />}>
        {transitions(
          (style, item) =>
            item && (
              <animated.div {...{style}}>
                <Calendar {...{date, dates, slider}} />
              </animated.div>
            )
        )}
      </Suspense>
    </div>
  );
}