Skip to content

Instantly share code, notes, and snippets.

@5t3ph
Last active November 28, 2022 13:16
Show Gist options
  • Save 5t3ph/38d6118139e4b601312c59c603081ca6 to your computer and use it in GitHub Desktop.
Save 5t3ph/38d6118139e4b601312c59c603081ca6 to your computer and use it in GitHub Desktop.
In Gatsby, leverage Reach Router's useLocation hook along with the query-string package to change user's selected theme, or expand to any values you need from the URL parameters, available on `location.search` from the useLocation hook.
import * as React from 'react';
import { useLocation } from '@reach/router';
import queryString from 'query-string';
const getSelectedTheme = (query) => {
const fallback = 'light';
if (query) {
const queriedTheme = queryString.parse(query);
const { theme } = queriedTheme;
// Ensure a valid expected value is passed
if (['light', 'dark'].includes(theme)) {
return theme;
}
return fallback;
}
return fallback;
};
const UserTheme = () => {
const location = useLocation();
const defaultTheme = (location.search && getSelectedTheme(location.search)) || 'light';
const [theme, setTheme] = React.useState(defaultTheme);
// rest of component, maybe creates/updates context, or updates a form setting
};
@adeleke5140
Copy link

Hello, would this be helpful if I wanted to add a query-string to the url? e.g in the url /about adding the query string /about?key=SOME_KEY
I've been trying to figure that out but can't seem to get it to work.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment