Open In App

How to Set Cookie in ReactJS ?

Last Updated : 01 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Cookies in React are used to set value in a key-value form which can be set in browser storage and used further for identifying the current user. The following example shows how to set the cookie in the ReactJS application, here we have taken the custom-cookie as key, which is set in the cookie with its value.

Approach

To set cookie in react we will use document.cookie property. We can also use external packages like js-cookie which simplify accessing cookie in react app.

Syntax:

// Setting cooking 
document.cookie = "name=value; expires=Thu, 01 Dec 2023 12:00:00 UTC; path=/";

// Accessing the cookie
const getCookie = (name) => {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
return null;
};

Steps to Create React Application

Step 1: Create a React application using the following command:

npx create-react-app setcookiedemo

Step 2: After creating your project folder i.e. setcookiedemo, move to it using the following command:

cd setcookiedemo

Project Structure:

Project Structure

List of dependencies in the package.json file are:

"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},

Example: This example demonstrates setting and accessing cookie in react with the help of window.cookie property.

JavaScript
// App.js

import React, { useState } from "react";

const App = () => {
	const [message, setMessage] = useState("");
	const [username, setUsername] = useState("");

	// Function to set a cookie
	const setCookieFunction = (name, value, days) => {
		let expires = "";
		if (days) {
			const date = new Date();
			date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
			expires = "; expires=" + date.toUTCString();
		}
		document.cookie = name + "=" + value + expires + "; path=/";
		setMessage(`Cookie set: ${name} = ${value}`);
	};

	// Function to get a cookie by name
	const getCookie = (name) => {
		const value = `; ${document.cookie}`;
		const parts = value.split(`; ${name}=`);
		if (parts.length === 2) return parts.pop().split(";").shift();
		return null;
	};

	// Function to update the cookie
	const updateCookie = () => {
		setCookieFunction("custom-cookie", username, 7); // Set cookie for 7 days
	};

	// Function to retrieve cookie and display it
	const displayCookie = () => {
		const customCookie = getCookie("custom-cookie");
		if (customCookie) {
			setMessage(`Retrieved Cookie Value: ${customCookie}`);
		} else {
			setMessage('No cookie found with the name "custom-cookie".');
		}
	};

	return (
		<div style={{ marginLeft: "200px" }}>
			<h2>Setting and Accessing Cookies in ReactJS</h2>
			<div>
				<span>Enter Value: </span>
				<input
					type="text"
					value={username}
					onChange={(e) => setUsername(e.target.value)}
					placeholder="Enter cookie value"
				/>
				<br />
				<button onClick={updateCookie}>Set/Update Cookie</button>
				<br />
				<button onClick={displayCookie}>Retrieve Cookie</button>
				<br />
				<span style={{ fontWeight: "bold", color: "red" }}>
					{message}
				</span>
			</div>
		</div>
	);
};

export default App;

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

Output--set-cookie-in-react


Next Article

Similar Reads