Load, save and remove cookies within your React application
You can also plug it directly with a Node.js request by adding just before the renderToString: reactCookie.plugToRequest(req, res);
(require the cookieParser middleware)
If you are within a non-browser or Node.js environment, you can use reactCookie.setRawCookie(req.headers.cookie)
NPM: npm install react-cookie
Bower: bower install react-cookie
CDN: https://cdnjs.cloudflare.com/ajax/libs/react-cookie/0.3.4/react-cookie.min.js
import React from 'react';
import cookie from 'react-cookie';
export default class MyApp extends React.Component {
constructor(props) {
super(props);
this.state = { userId: cookie.load('userId') };
}
onLogin(userId) {
this.state.userId = userId;
cookie.save('userId', userId);
}
onLogout() {
cookie.remove('userId');
}
render() {
return (
<LoginPanel onSuccess={this.onLogin.bind(this)} />
);
}
}
var React = require('react');
var cookie = require('react-cookie');
var MyApp = React.createClass({
getInitialState: function() {
return { userId: cookie.load('userId') };
},
onLogin: function(userId) {
this.state.userId = userId;
cookie.save('userId', userId);
},
onLogout: function() {
cookie.remove('userId');
},
render: function() {
return (
<LoginPanel onSuccess={this.onLogin} />
);
}
});
module.exports = MyApp;
If you have async requests going on the server side you need to save
the handle of the request returned by reactCookie.plugToRequest(req, res, {useHandles : true});
(probably in the context) and use it as opt={handle : thisRequestId}
in all the methods.
TODO: Add example goes here
You can use react-cookie with anything by using the global variable reactCookie
.
Note that window
need to exists to use reactCookie
.
Support all the cookie options from the RFC.
cookie path
absolute expiration date for the cookie (Date object)
relative max age of the cookie from when the client receives it (seconds)
domain for the cookie
true or false
true or false
This project is under the MIT license. You are free to do whatever you want with it.