All files / ts/components/banners cookie-banner.tsx

100% Statements 25/25
100% Branches 6/6
100% Functions 4/4
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 8432x 32x 32x 32x   32x                                                                 32x         5x   5x         32x 6x 6x 6x 6x 6x 12x 6x     6x   6x                       5x 1x 1x       32x   32x  
import * as classNames from 'classnames';
import * as cookie from 'cookie';
import * as React from 'react';
import { HTMLProps, PureComponent } from 'react';
import { ComponentProps } from '../../types';
import Banner from './banner';
 
export interface CookieBannerRenderProps {
  dismiss: () => void;
}
 
export type Render = (
  props: CookieBannerRenderProps
) => React.ReactElement<any>;
 
export interface CookieBannerProps
  extends ComponentProps,
    HTMLProps<HTMLElement> {
  /**
   * Takes a component as a function and renders as a child
   */
  render: Render;
  /**
   * Positions the element at the 'top' or 'bottom' of the screen
   * @default 'bottom'
   */
  position?: 'top' | 'bottom';
}
 
export interface CookieBannerState {
  dismissed: boolean;
}
 
/**
 * A [Banner](#banner) component that is permanently dismissed after setting a cookie.
 * This component takes a render prop, which can be a component or function, that is passed a dismiss prop
 * which you can then apply as an onClick prop to an element of your choice.
 */
export class CookieBanner extends PureComponent<
  CookieBannerProps,
  CookieBannerState
> {
  public constructor(props: CookieBannerProps) {
    super(props);
 
    this.state = {
      dismissed: Boolean(cookie.parse(document.cookie)['cookies-accepted']),
    };
  }
 
  public render() {
    const {
      ref,
      className,
      children,
      render,
      position = 'bottom',
      ...remainingProps
    } = this.props;
 
    const { dismissed } = this.state;
 
    return (
      <Banner
        {...remainingProps}
        position={position}
        open={!dismissed}
        className={classNames('cookie-banner', className)}
      >
        {render && render({ dismiss: this.setCookie })}
      </Banner>
    );
  }
 
  private setCookie = () => {
    document.cookie = cookie.serialize('cookies-accepted', 'true');
    this.setState({
      dismissed: true,
    });
  };
}
 
export default CookieBanner;