Creating the app
npx create-next-app@latest example-blog &&
cd example-blog
This will...
- Create a NextJS app in a folder named
example-blog
- Put you inside of the folder you just created
Installing Styled Components
npm i --save styled-components &&
npm i --save-dev babel-plugin-styled-components
This will...
- Install
styled-components
into ourexample-blog
folder - Install a babel plugin that allows us to see class names in the browser (with additional work to come)
Now open up whichever editor you use, I will be using Visual Studio Code, and open the pages/index.js
file.
an easy way to do this is to go back to your console and type code .
to open up the folder in VSC
To explain what the babel plugin does, I'm going to create a styled component for this page.
Under the imports that already exist, add this code.
import styled from 'styled-components';
const Container = styled.div`
background-color: black;
color: white;
`
What this does is...
- Import the ability to create
styled
components - Create a variable named
Container
that we declare is a styleddiv
- Assign plain CSS to our
Container
variable
Next I am going to replace an element with our new Container
div. Click the arrow next to the outermost div to collapse it.
Then I am going to replace those 2 lines with this...
Now if you go to your console and type
npm run dev
You will see the basic NextJS homepage, but now with a black background and white text that we assigned in our styled component.
But we have a problem, our div we created now just has random numbers and letters for a class name. There's no way of figuring out where an element is getting its styling from. This is where that babel plugin comes into play.
In your root folder, create a file name .babelrc
And inside of that file add this code.
{
"presets": ["next/babel"],
"plugins": [["styled-components", { "ssr": true, "displayName": true }]]
}
Now hit ctrl-c in your console to stop your server, and type npm run dev
again.
This time in your console you should see that your div now has a class name that tells you which folder the styled component
lives in (pages) and what the name of that component is (Container)
Spring Cleaning
To clean up our project a little we are going to remove the files we won't be using with this guide.
pages/api
folder can be deleted
styles/Home.modules.css
file can be deleted
I am also going to go ahead and import 'Poppins' font and place it inside of my globals.css file for the body to apply it to everything.
- This will break your app because
index.js
is using these styles. - To fix this you can just remove everything from the return and add
<h1>Hello</h1>
or anything you want (we will be adding content to this file soon)
Top comments (0)