Get cookie with react
Solution 1:
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
Solution 2:
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
Solution 3:
I'd recommend using universal-cookie
as its simpler to use. Mind you, cookies have 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
Solution 4:
There is no need for a third party npm package. You can use plain JS to extract the cookie. Here is a custom function for that:
function getCookie(key) {
var b = document.cookie.match("(^|;)\\s*" + key + "\\s*=\\s*([^;]+)");
return b ? b.pop() : "";
}