How to use js-cookie to store data in cookies in react js
Today in this tutorial we will learn about how to use js-cookie to store data in cookies in react js. JS-Cookie is a lightweight JavaScript library that allows you to store and retrieve data as cookies in the client’s browser. So here’s a tutorial on how to use JS-Cookie in React.js.
Requirements
Step 1: Installation
To install it, go to your project root directory and run the following command in your terminal.
npm install js-cookie
Step 2: Import
Import the JS-Cookie library in your React component.
import Cookies from 'js-cookie';
Step 3: Set Cookie
You can set a cookie using the set() method. This method takes three parameters the cookie name, the value to be stored, and an options object.
Cookies.set('name', 'value', { expires: 7 });
Step 4: Get Cookie
You can retrieve the value of a cookie using the get() method. This method takes the name of the cookie as a parameter.
const name = Cookies.get('name');
Step 5: Remove Cookie
You can remove a cookie using the remove() method. This method takes the name of the cookie as a parameter.
Cookies.remove('name');
Step 6: Example
Below is an example. Simply copy and paste the code into your react component.
import Cookies from "js-cookie";
function App() {
// Method to set data in cookies which will expire in 7 days
const SetCookie = () => {
Cookies.set("token", "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9", {
expires: 7,
});
};
// Method to get data from cookies
const GetCookie = () => {
alert(Cookies.get("token"));
};
// Method to remove data from cookies
const RemoveCookie = () => {
Cookies.remove("token");
};
return (
<div style={{ textAlign: "center" }}>
<h6>1. Click on Set Cookie to set data in cookies</h6>
<h6>2. Click on Get Cookie to display the data</h6>
<h6>2. Click on Remove Cookie to remove data from cookies</h6>
<button onClick={SetCookie}>Set Cookie</button>
<button onClick={GetCookie}>Get Cookie</button>
<button onClick={RemoveCookie}>Remove Cookie</button>
</div>
);
}
export default App;
Step 7: Explaination
In the above example we have created three method to show how data are set, get and remove from cookies using js-cookie. Each code has been explained using code commenting.
For any query, you can get in touch with me via LinkedIn
Below you can find the sample GitHub Repository and demo on codesandbox.