How to get the cookie in React
In this tutorial, we are going to learn about how to get the cookie from a browser in React using the react-cookie package.
Installing the react-cookie package
The react-cookie package helps us to get and set the cookies from the browser.
Let’s install it, by running the following command.
npm install react-cookie
Getting the cookie with React hooks
First, import the CookiesProvider
component from the react-cookie package and wrap your root app component with it.
import React from "react";
import ReactDOM from "react-dom";
import { CookiesProvider } from "react-cookie";import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<CookiesProvider> <App /> </CookiesProvider>, rootElement
);
Now, inside your React component, you can access the cookie by using a useCookies()
hook.
import React from "react";
import { useCookies } from "react-cookie";
export default function App() {
const [cookies, setCookie] = useCookies();
return (
<div className="App">
<h1>React cookies</h1>
{cookies.user && <p>{cookies.user}</p>} </div>
);
}
The
cookies
object is holding the all cookies, you have created in your app.
In class-based components, you can get the cookie by using a withCookies()
higher-order component.
import React, { Component } from "react";
import { withCookies } from "react-cookie";
class App extends Component {
state = { // getting the cookie
user: this.props.cookies.get("user") || "" };
render() {
const { user } = this.state; return (
<div className="App">
{user && <p>{user}</p>} </div>
);
}
}
export default withCookies(App);
These are some cases you can’t get a cookie in React:
-
If you don’t set a cookie path as
/
then you can’t access a cookie from all pages. -
If you set an
httpOnly
cookie to the response, then you can’t access it inside the react app, because the browser directly embeds the cookie to an HTTP header.