To read a cookie in a React application, you can access the document.cookie
property and parse the cookies to retrieve the desired value. Here’s how you can do it:
import React from 'react';
function ReadCookie() {
const readCookie = (name) => {
const cookieString = document.cookie;
const cookies = cookieString.split('; ');
for (const cookie of cookies) {
const [cookieName, cookieValue] = cookie.split('=');
if (cookieName === name) {
return cookieValue;
}
}
return null; // Cookie not found
};
const myCookieValue = readCookie('myCookie');
return (
<div>
<p>Value of 'myCookie': {myCookieValue}</p>
</div>
);
}
export default ReadCookie;
In this example, the ReadCookie
component defines the readCookie
function, which takes the name of the cookie as an argument. It reads the document.cookie
property, splits it into individual cookies using the semicolon and space separator, and then iterates through the cookies to find the one with the matching name.
The component then displays the value of the ‘myCookie’ cookie.
Keep in mind that working with cookies directly using document.cookie
has limitations and potential security considerations. Modern applications often use libraries or utilities for cookie management to handle more complex scenarios and ensure proper security practices. If you’re working with cookies extensively, consider using a library like js-cookie
or similar.