Community powered answers to your dev questions

Change page url path based on theme options

posted: 2020 January 22nd

category: gatsby

Edit this post on GitHub.


When creating themes we can ship with our page paths set, but sometimes we want to give the user the option to change that path. For example, if we had a path that was awesomePage but our theme consumer wanted to change that to myPage, then we can access the users choice via the options they pass into our theme.

In our gatsby-node.js file we can take advantage of the createPages function and access the plugin options. From there we can run a check to see if the user passed in a custom url, if they did we can create that page based off of our original page, thus replacing the original pages path.

The user consuming our theme would do something like this:

1module.exports = {
2 plugins: [
3 {
4 resolve: 'gatsby-theme-boop',
5 options: {
6 customUrl: 'myPage',
8 }
9 ]

Then in our themes gatsby-config.js file we can accept the option:

1module.exports = (options) => {
2 const {
3 customUrl
4 } = options;
5 plugins: [...]

Then in our gatsby-node.js file we can use the createPages function and check if the theme consumer passed in the option:

1exports.createPages = async ({ actions: { createPage } }, pluginOptions) => {
3 if (pluginOptions.customUrl) {
4 createPage({
5 path: `/${pluginOptions.customUrl}/`,
6 component: require.resolve('./src/templates/awesomePage.js')
7 })
8 }
9 }

The consumer of the theme would then be able to access the page from /myPage instead of /awesomePage

Author: Rich Haines