Get cookie with react
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
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