70 %
Chris Biscardi

Applying theme options using React Context

If we're trying to use (and let other people use) values from the options that get passed into our theme inside of React components, then we can use Webpack's DefinePlugin but a more idiomatic solution can be to use React context!

First we'll create a file that represents our next context.

"src/context.js"
JS
export const GatsbyThemeBlogOptionsContext = React.createContext(
{}
);

We can then import that context in our theme and use it in the wrapRootElement lifecycle in the gatsby-browser.js and gatsby-ssr.js files.

"gatsby-browser.js"
JS
import { GatsbyThemeBlogOptionsContext } from "./src/context";
export const wrapRootElement = ({ element }, options) => (
<GatsbyThemeBlogOptionsContext.Provider value={options}>
{element}
</GatsbyThemeBlogOptionsContext>
);

Then in our own components that need to switch render, or in any user's site, we can import and take advantage of the context.

JS
import { GatsbyThemeBlogOptionsContext } from "gatsby-theme-blog/src/context";
export default props => {
const { enableSidebar } = useContext(
GatsbyThemeBlogOptionsContext
);
return (
<section>
{enableSidebar && (
<aside>
<ul>...</ul>
</aside>
)}
<main>some content</main>
</section>
);
};