Home Programming Methods to get the cookie in React

Methods to get the cookie in React

0
Methods to get the cookie in React

[ad_1]

On this tutorial, we’re going to find out about get the cookie from a browser in React utilizing the react-cookie package deal.

The react-cookie package deal helps us to get and set the cookies from the browser.

Let’s set up it, by working the next command.

First, import the CookiesProvider part from the react-cookie package deal and wrap your root app part with it.

index.js

import React from "react";
import ReactDOM from "react-dom";
import { CookiesProvider } from "react-cookie";import App from "./App";

const rootElement = doc.getElementById("root");
ReactDOM.render(
  <CookiesProvider>    <App />  </CookiesProvider>,  rootElement
);

Now, inside your React part, you possibly can entry the cookie by utilizing a useCookies() hook.

App.js

import React from "react";
import { useCookies } from "react-cookie";
export default perform App() {
  const [cookies, setCookie] = useCookies();
  return (
    <div className="App">
      <h1>React cookies</h1>
      {cookies.consumer && <p>{cookies.consumer}</p>}    </div>
  );
}

The cookies object is holding the all cookies, you might have created in your app.

At school-based elements, you will get the cookie by utilizing a withCookies() higher-order part.

App.js

import React, { Element } from "react";
import { withCookies } from "react-cookie";
class App extends Element {

  state = ;

  render() {
    const { consumer } = this.state;    return (
      <div className="App">
        {consumer && <p>{consumer}</p>}      </div>
    );
  }
}

export default withCookies(App);

These are some circumstances you possibly can’t get a cookie in React:

  • For those who don’t set a cookie path as / then you possibly can’t entry a cookie from all pages.

  • For those who set an httpOnly cookie to the response, then you possibly can’t entry it contained in the react app, as a result of the browser immediately embeds the cookie to an HTTP header.

[ad_2]

LEAVE A REPLY

Please enter your comment!
Please enter your name here