Get cookie with react

此生再无相见时 提交于 2019-12-04 22:53:14

You can use js-cookie package and can install it using npm install js-cookie --save command.

import React from 'react';
import Cookies from 'js-cookie';

class App extends React.Component {
     this.state = {
        username: Cookies.get('username')
     }

//  more code....
}  

Documentation : https://github.com/js-cookie/js-cookie

NPM : https://www.npmjs.com/package/js-cookie

I'd recommend using universal-cookies as its simpler to use. Mind you, cookies has nothing to do with React. They are stored on the browser and you could use the browser's default API to get cookies.

Here is an example how you can use universal-cookies

import React from 'react';
// other imports...
import Cookies from 'universal-cookie';

const cookies = new Cookies();

class App extends React.Component {
     this.state = {
        username: cookies.get('username')
     }

//  more code....   

source: https://www.npmjs.com/package/universal-cookie

If all you want is to get the cookie value by key, I would suggest using plain javascript without any dependencies.

In this example, it gets the cookie value by the key "username" with the help of Regex.

let cookieValue = document.cookie.replace(/(?:(?:^|.*;\s*)username\s*\=\s*([^;]*).*$)|^.*$/, "$1");

https://developer.mozilla.org/en-US/docs/Web/API/document/cookie#Example_2_Get_a_sample_cookie_named_test2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!