Skip to content

Instantly share code, notes, and snippets.

@derekclair
Forked from keatz55/PostPreview.js
Created May 31, 2018 07:52
Show Gist options
  • Save derekclair/9a69cfff46685d90f6f362a9fd904514 to your computer and use it in GitHub Desktop.
Save derekclair/9a69cfff46685d90f6f362a9fd904514 to your computer and use it in GitHub Desktop.
Context API - Simple Session Example
import React from 'react';
import Paper from 'material-ui/Paper';
import withSession from '../hocs/withSession';
class PostPreview extends React.PureComponent {
render() {
const { session } = this.props;
return (
<Paper square elevation={1}>
...
</Paper>
);
}
}
export default withSession(PostPreview);
import React from 'react';
const SessionContext = React.createContext(null);
export default SessionContext;
import React from 'react';
import { MuiThemeProvider } from 'material-ui/styles';
import CssBaseline from 'material-ui/CssBaseline';
import SessionContext from './contexts/session';
import getPageContext from './getPageContext';
function withRoot(Component) {
class WithRoot extends React.Component {
static getInitialProps = async ctx => {
const { req } = ctx;
const isServer = !!req;
let session = null;
if (!isServer) {
const sessionEl = document.getElementById('session');
if (sessionEl) {
session = JSON.parse(sessionEl.textContent);
}
} else session = req.session;
if (Component.getInitialProps) {
const compProps = await Component.getInitialProps({...ctx, session});
return { ...compProps, session };
}
return { session };
};
componentWillMount() {
this.pageContext = this.props.pageContext || getPageContext();
}
componentDidMount() {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side');
if (jssStyles && jssStyles.parentNode) {
jssStyles.parentNode.removeChild(jssStyles);
}
}
pageContext = null;
render() {
const { session } = this.props;
return (
<SessionContext.Provider value={session}>
{/* MuiThemeProvider makes the theme available down the React tree thanks to React context. */}
<MuiThemeProvider
theme={this.pageContext.theme}
sheetsManager={this.pageContext.sheetsManager}
>
{/* Reboot kickstart an elegant, consistent, and simple baseline to build upon. */}
<CssBaseline />
<Component {...this.props} />
</MuiThemeProvider>
</SessionContext.Provider>
);
}
}
return WithRoot;
}
export default withRoot;
import React from 'react';
import SessionContext from '../contexts/session';
export default function withSession(Component) {
return function SessionComponent(props) {
return (
<SessionContext.Consumer>
{session => <Component {...props} session={session} />}
</SessionContext.Consumer>
);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment