Using Cookies with React, Redux and React Router 4

Bonus: Passing Cookies and Redux Actions to Formik handlers

Installation

Configuration

...
import { CookiesProvider } from 'react-cookie';
let initialStore = {
...
};
const store = createStore(rootReducer, initialStore);ReactDOM.render( <CookiesProvider>
<BrowserRouter>
<Provider store={store}>
<App />
</Provider>
</BrowserRouter>
</CookiesProvider>,
document.getElementById('root'));
...
import { withCookies } from 'react-cookie';
class App extends Component {render() {
return (
<div>
<Switch>
<Route
path="/"
render={() => (<HomeContainer cookies={this.props.cookies}/>)}
/>
</Switch>
</div>
);
}
}
export default withCookies(App);
component={HomeContainer}
render={() => (<HomeContainer cookies={this.props.cookies}/>)}

HomeContainer (Redux container)

const mapStateToProps = (state, ownProps) => {
return({
state: state,
cookies: ownProps.cookies,
});
};
class Home extends React.Component {
...
}
const mapStateToProps = (state, ownProps) => {
return({
state: state,
cookies: ownProps.cookies,
});
};
export const HomeContainer = connect(
mapStateToProps,
null
)(Home);
export default HomeContainer;

Get and Set Cookies

//get this.props.cookies
const { cookies } = this.props;
//setting a cookie
cookies.set('name', 'Ross', { path: '/' });
//getting a cookie
cookies.get('name');

Passing the cookie prop into Formik handlers

const handleSubmit = (values, { props = this.props, setSubmitting }) => {   //handle form submission
...
//set cookie
props.cookies.set('name', values.name, { path: '/' });

setSubmitting(false);

//update state, do something else...
props.handleStateFromRedux(Object.assign({}, values));
}

<Formik
onSubmit={handleSubmit}
...
/>

Programmer and Author. Director @ JKRBInvestments.com. Creator of LearnChineseGrammar.com for iOS.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store