To set and unset cookies in a React application, you need to work with the document.cookie
property to manage the cookie data. Here’s how you can set and unset cookies in React:
Setting a Cookie:
import React from 'react';
function SetCookie() {
const setCookie = () => {
document.cookie = "myCookie=myValue; expires=Fri, 31 Dec 2023 23:59:59 GMT; path=/";
};
return (
<div>
<button onClick={setCookie}>Set Cookie</button>
</div>
);
}
export default SetCookie;
In this example, the SetCookie
component defines the setCookie
function that sets a cookie named “myCookie” with the value “myValue” and an expiration date. Adjust the expiration date, path, and other attributes as needed.
import React from 'react';
function UnsetCookie() {
const unsetCookie = () => {
document.cookie = "myCookie=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/;";
};
return (
<div>
<button onClick={unsetCookie}>Unset Cookie</button>
</div>
);
}
export default UnsetCookie;
In this example, the UnsetCookie
component defines the unsetCookie
function that unsets (deletes) a cookie named “myCookie” by setting its expiration date to a past time.
Remember 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.