Giter Club home page Giter Club logo

react-cookie-banner's Introduction

Build Status

React Cookie Banner

A cookie banner for React that can be dismissed with a simple scroll. Because fuck the Cookie Law that's why.

(If you really want to annoy your users you can disable this feature but this is strongly discouraged!).

import CookieBanner from 'react-cookie-banner';

React.renderComponent(
  <div>
    <CookieBanner
      message="Yes, we use cookies. If you don't like it change website, we won't miss you!"
      onAccept={() => {}}
      cookie="user-has-accepted-cookies" />
  </div>,
  document.body
);

Live Examples

Install

npm install --save react-cookie-banner

or using yarn:

yarn add react-cookie-banner

API

You can see CookieBanner's props in its own README.md

Style

react-cookie-banner comes with a nice default style made using inline-style.

Of course, you can customize it as you like in several ways.

Based on how many changes you want to apply, you can style react-cookie-banner as follows:

You like the original style and you wish to make only a few modifications

Why spending hours on the CSS when you have such a nice default style? :)

In this case you can:

1) Override the predefined inline-styles

In this example we change the message font-size and make the banner slightly transparent with the styles prop:

<CookieBanner
  styles={{
    banner: { backgroundColor: 'rgba(60, 60, 60, 0.8)' },
    message: { fontWeight: 400 }
  }}
  message='...'
/>

See src/styleUtils.ts for a complete list of overridable style objects.

2) Beat it with good old CSS (or SASS)

The banner is structured as follows:

<div className={this.props.className + ' react-cookie-banner'}
  <span className='cookie-message'>
    {this.props.message}
    <a className='cookie-link'>
      Learn more
    </a>
  </span>
  <button className='button-close'>
    Got it
  </button>
</div>

You can style every part of it using the appropriate className:

.your-class-name.react-cookie-banner {
  background-color: rgba(60, 60, 60, 0.8);

  .cookie-message {
    font-weight: 400;
  }
}

You need to heavily adapt the style to your application

Your creative designer wants to change the style of the cookie banner completely? Don't worry, we got your covered!

If you need to re-style it, you can:

1) Disable the default style and use your CSS

You may disable the default style by simply setting the prop disableStyle to true:

<CookieBanner disableStyle={true} />

Now you can re-style the cookie banner completely using your own CSS.

2) Use your own cookie banner!

Don't like the layout either? You can use your own custom cookie banner component by passing it as children and still let react-cookie-banner handle the hassle of managing cookies for you :)

<CookieBanner>
  {(onAccept) => (
    <MyCustomCookieBanner {...myCustomProps} onAccept={onAccept} /> {/* rendered directly without any <div> wrapper */}
  )}
</CookieBanner>

Cookies manipulation

react-cookie-banner uses universal-cookie to manipulate cookies.

You can import the Cookies class and use it as follows:

import { Cookies } from 'react-cookie-banner'

const cookies = new Cookies(/* Your cookie header, on browsers defaults to document.cookie */)

// simple set
cookie.set('test', 'a')
// complex set - cookie(name, value, ttl, path, domain, secure)
cookie.set('test', 'a', {
  expires: new Date(2020-05-04)
  path: '/api',
  domain: '*.example.com',
  secure: true
})
// get
cookies.get('test')
// destroy
cookies.remove('test', '', -1)

Please refer to universal-cookie repo for more documentation.

Server side rendering (aka Universal)

react-cookie-banner supports SSR thanks to react-cookie. If you want to support SSR, you should use the CookieProvider from react-cookie and the CookieBannerUniversal wrapper:

import { Cookies, CookiesProvider, CookieBannerUniversal } from 'react-cookie-banner'

const cookies = new Cookies(/* Your cookie header, on browsers defaults to document.cookie */)

<CookiesProvider cookies={cookies}>
  <CookieBannerUniversal />
</CookiesProvider>

react-cookie-banner's People

Contributors

adamsandle avatar art-smi avatar corwincz avatar danielegallingani avatar davkal avatar f4b1n0u avatar francescocioria avatar gabro avatar giogonzo avatar lvauvillier avatar richardwestenra avatar veej avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-cookie-banner's Issues

Using this libray with DotNetCore ASP.NET #C React Redux

It took me sometime to figure out how to use this with SSR for our project, hopefully it goes to show someone.

  1. For your component with cookies defined you only need to import CookieBannerUniversal.
    Use as below
    <CookieBannerUniversal {...props} >
    {this.props.children}
    </

  2. In your Client.js

ReactDOM.render(
        <Provider store={store}>
            <CookiesProvider>
                <ConnectedRouter history={history} location children={routes} />
            </CookiesProvider>
        </Provider>
        ,
        document.getElementById('app')
    );

  1. Server.js or boot-server.js
const convertCookieToString = (cookieArray) => {
//do something to convert your array to normalized string.
//e.g "a=1;b=2"
return arrayTostring
}

const serverCookiesArray = array({'a': '1'}, {'b' : '2'} ) 

const cookies = new Cookies(convertCookieToString(serverCookiesArray))
 const app = (
            <Provider store={store}>
                <CookiesProvider cookies={cookies}>
                <StaticRouter basename="/" context={routerContext} location={params.location.path} children={routes} />
                </CookiesProvider>
           </Provider>
        );

const render = renderToString(app)

NOTE: Make sure your server cookies array matches that found using document.cookie

Cookie Law Update - Scrolling is no longer to be considered an explicit consent

Updated cookie law:
https://edpb.europa.eu/sites/edpb/files/files/file1/edpb_guidelines_202005_consent_en.pdf

actions such as scrolling or swiping through a webpage or similar user activity will not under any circumstances satisfy the requirement of a clear and affirmative action: such actions may be difficult to distinguish from other activity or interaction by a user and therefore determining that an unambiguous consent has been obtained will also not be possible. Furthermore, in such a case, it will be difficult to provide a way for the user to withdraw consent in a manner that is as easy as granting it.

Users should be able to dismiss banner by clicking anywhere on it

This can be already implemented by doing

<CookieBanner>
  {(onAccept) => <div onClick={onAccept}><Content {...templateProps} /></div>
</CookieBanner>

But as more than one person has this use case, it would be better to support it natively with a dedicated prop like dismissOnClick

Message prop prop-types configuration.

Proptypes complains about sending a message prop to component different than string.

Warning: Failed prop type: Invalid prop 'message' of type 'object' supplied to 'CookieBanner', expected 'string'. in CookieBanner

I'm sending a span with html to allow links (also styled text) to the message prop. It works but proptypes complains with previous annoying warning. This is my message:

<span dangerouslySetInnerHTML={{ __html: '<a href="https://www.google.com">Link!</a>' }} />

Can the component be updated to allow multiple prop types for message prop, not only strings?

Thank you.

Use official typings for `react-cookie`

requirements

react-cookie is about to add official typings to their lib: bendotcodes/cookies#124.

As soon as they merge and publish them, we should remove our react-cookie.d.ts in favour of them

specs

remove react-cookie.d.ts and update react-cookie to the version with TS typings

misc

{optional: other useful info}

Renew example

requirements

Freshen up the example with a brand-new style.

specs

mockup: click

misc

{optional: other useful info}

Cookie expiration date

Hi,

The current cookie expiration date is set to 1 year after the acceptance of the cookie. Does the law require yearly approval, or is it just a default for the code? (and if so, couldn't the cookie be set with a much expiration date way later in time, so as to not bother users again a year after acceptance?)

Accessibility Improvement: add parameter for button label

As far as I can tell there's no way to add custom attributes to the close cookie banner button. Would be great if html attributes such as title or aria-label (ie <button aria-label='Close cookies statement' class='button-close'>) could be added for screen readers where the icon isn't sufficient.

It should also be noted that the icon inside the button should have an aria-hidden="true" attribute

Template and cookie logic should live in different components

requirements

Currently the banner template and the cookie management logic are not completely independent.
This may cause conflicts in case a user needs to add a layer between the two (ex: #28 ).

specs

We should separate the cookie management logic and the banner template in two different components: CookieBanner (default) and Content.

The Content component would be exported as well and used as default by CookieBanner and it would accept any template related prop.

misc

After this separation the issue described in #28 could be solved by doing:

<CookieBanner {...cookieProps}>
  {(onAccept) => <div onClick={onAccept}><Content {...templateProps} /></div>}
</CookieBanner>

Server side rendering issues

Hi guys, can we merge the waiting pull request to use react-cookies with SSR?

Currently having invalid checksum issues with server side rendering.

Component only return null

I like to use this with gatsby (they use still react 0.15.x), but I can't get its working. The code is in src/layout/index.js - It's a child of the main Container. I've tried also to add a <div> wrapper.

I can see the component with the chrome developer react extension, but it doesn't render anything, it just returns null. I saw the package.js like to have react ^0.16 so I've downgraded to react-cookie-banner v0.0.18. But still exactly same, nothing. Any idea?

Alwas shows on Mobile (Chrome Android)

I haven't tested extensively.
It seems not to be working in Chrome for Android. Other browsers might be affected by I have not been able to check.

I click the Got it button, it hides but when I reload the page, it is shown again.

Banner not being displayed

My component:

import { Cookies, CookiesProvider, CookieBannerUniversal } from 'react-cookie-banner';

const cookies = new Cookies();

export default () => (
  <CookiesProvider cookies={cookies}>
    <CookieBannerUniversal         
      dismissOnScroll={false}
    />
  </CookiesProvider>
)

I get the browser message Warning: Did not expect server HTML to contain a <div> in <div>.

Even using the standard non SSR method it does not show with the same message. I'm using Next.js

Typings problem with 2.0.0

Hi, I've updated to the recent version and now I am seeing this error:

ERROR in [at-loader] ./node_modules/react-cookie-banner/lib/CookieBanner.d.ts:4:10
TS2305: Module ''react-cookie'' has no exported member 'Cookies'.
ERROR in [at-loader] ./node_modules/react-cookie-banner/lib/index.d.ts:5:10
TS2305: Module ''react-cookie'' has no exported member 'Cookies'.

Seems simple enough to fix, I reverted to the previous version for now.

Live Examples are broken

description

Live Examples link in the README sends you to https://react-components.buildo.io/#cookiebanner which leads to the following stacktrace:

Uncaught TypeError: o.forwardRef is not a function
    at Object.<anonymous> (bundle.9737c2fd.js:150)
    at __webpack_require__ (bundle.9737c2fd.js:1)
    at Object.<anonymous> (bundle.9737c2fd.js:150)
    at __webpack_require__ (bundle.9737c2fd.js:1)
    at render (bundle.9737c2fd.js:155)
    at Module.<anonymous> (bundle.9737c2fd.js:155)
    at __webpack_require__ (bundle.9737c2fd.js:1)
    at Object.<anonymous> (bundle.9737c2fd.js:49)
    at __webpack_require__ (bundle.9737c2fd.js:1)
    at bundle.9737c2fd.js:1

misc

I guess the problem is not browser specific in this case, however i still tested a few just to be sure:

  • Vivaldi 2.4.1488.35
  • Microsoft Edge 44.17763.1.0
  • Internet Explorer 11
  • Google Chrome 73.0.3683.86
  • Mozilla Firefox 66.0.2

They all lead to the same Error.

Documentation of link prop is obsolete

Current documentation of link prop found here is out-dated. Current implementation required JSX element instead of object - as found here

Documentation can be updated this way (line 11):

| **link** | ```<a href="http://demo.url" target="_blank">Link text</a>``` |  | *optional*. JSX element to link to your cookie-policy page |

Originaly I wanted to create PR for this issue, but it is not possible to push new branch to repository.

Incorrect peer dependency.

Hello

Yarn complains about this dependency lib: react-addons-clone-with-props.

warning "react-cookie-banner > [email protected]" has incorrect peer dependency "react@^0.14.8".

Can be updated? I'm using react 16.5.1.

Thanks.

import in v1.0.0 is broken

description

import CookieBanner from 'react-cookie-banner' does not work in 1.0.0

how to reproduce

  • {optional: describe steps to reproduce bug}

specs

{optional: describe a possible fix for this bug, if not obvious}

misc

{optional: other useful info}

Refactor in TypeScript!

requirements

Refactor in TypeScript!

specs

Refactor in TypeScript!

misc

{optional: other useful info}

Warning: componentWillReceiveProps has been renamed

Getting this warning

`Warning: componentWillReceiveProps has been renamed, and is not recommended for use. See https://fb.me/react-unsafe-component-lifecycles for details.

  • Move data fetching code or side effects to componentDidUpdate.
  • If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state
  • Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run npx react-codemod rename-unsafe-lifecycles in your project source folder.

Please update the following components: CookieBanner`

React15 throws warning for unknown prop

description

image

how to reproduce

  • {optional: describe steps to reproduce defect}

specs

omit CookieBanner's props before passing them to div wrapper

misc

{optional: other useful info}

Accessibility improvements: Button elements & a rel attributes

requirements

copy pasted from this PR:

  1. Change the default close button & icon elements to use <button> elements, either instead of a div, or as an added wrapper around the <i> icon element.
    This is mainly to make these elements focusable, tabbable and clickable with a keyboard. Among other things, this change will improve accessibility for visually-impaired screenreader users, as well as users with reduced motor skills who might prefer to use a keyboard instead of a mouse.
  2. Add 'rel' attribute param to the link option. Allowing developers to add the rel attribute will enable them to set rel="noopener noreferrer" on external links, especially those which open in a new tab. This helps mitigate a security vulnerability and potentially improves performance too.
  3. Improve contrast of button foreground/background colours, to help meet WCAG text contrast guidelines.

specs

{optional: describe technical specs to implement this feature, if not obvious}

misc

{optional: other useful info}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.