Add Theme-ui to Next
How to add theme-ui to NEXTjs
Today i decided to finally take the plunge and start learning NEXTjs. I've been working with Gatsby for two over years now, have created many sites and themes and generally feel very comfortable in that environment. But it was time, finally to bite the bullet and see what all the fuss was about!
When i build Gatsby sites i always style them with theme-ui. Its my favorite way to style websites as it allows you to globally control your sites styles from one file, lets you work responsively using simple array syntax and works wonderfully well with Gatsby. I was curious though, how would it play with NEXTjs? Would the setup be as simple as with Gatsby? After all, and i quote the corgi master himself Chris Biscardi "Theme-ui is just a set of react context providers and a pragma". How hard could it be?
Well it turns out not very hard, once you have figured it out that is.
I started with the starter tutorial on the NEXTjs website and got things up and running in no time. Its very impressive NEXTjs, though i haven't dived too deep into it yet. But i digress, when we add theme-ui to our website we generally want to wrap our root element or page with it's context. The only problem was, when i spun up the NEXTjs tutorial example, there was no root element, no app.js. Only a pages folder, some components and a public folder.😕
The answer turned out to be overriding the base app.js file and providing the context that way. Lets dive into some code..
Create our theme file
Create a new folder called components and a file named theme.js
We are just going to test if it works by changing the color of some text so no need to add any more than some colors for now.
Overriding the base app.js
Create a new file inside of pages and name it _app.js
The docs explain this very well so i will quote them here:
The Component prop is the active page, so whenever you navigate between routes, Component will change to the new page. Therefore, any props you send to Component will be received by the page.
Lets try out our new colors! Open the index.js file located in the pages folder and use the sx prop and add a p tag.
Now if we run yarn dev we should see the magic happen....
Nothing happened! 🥺
Thats because we forgot to add the jsx pragma! I spent an hour trying to figure out why it wasn't working and that was the reason.
You're welcome 😘