Chris Biscardi

moon indicating dark mode
sun indicating light mode

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.

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.

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.

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>
);
};