Migrating To NextJS From React
Want to switch to next without starting everything from scratch?
- Next takes care of routing for you.
- Faster Rendering.
- Supports typescript, tailwind , APIs .
- Has SEO (Search Engine Optimization)
- Has Image Optimization.
Delete React Dependencies like “react-scripts” , “react-router”, “web-vitals” from package.json.
This can be done by uninstalling the package
npm uninstall <packagename>
Remove index.html from public as well. We won’t be needing that for nextjs.
remove all node_modules if you used create-react-app for your project.
Node_modules has tons of useless packages which we are not even going to use. Better delete than wasting space.
Install npm package for Next
We removed react-scripts in first step. How do we run our project now?
Inside package.json change the commands to:
To run project do the following in terminal:
npm run dev
Create “components” , “pages” and “public” folder in your project folder.
It should look like:
Make sure you move your media ( images, videos, SVGs) to public folder under “assets”. (When you put something inside public it is accessible to all components of next. Now instead of long source of file you just write /foldername/filename and you are good to go! )
This Folder contains repeating components which we use in all pages. Like
- Header (Navigation Bar)
- Layout (Rather than making header and footer for every page we can define it in a layout and it will be displayed by default on all pages.
Layout.js looks like
This folder contains all the pages which we make. by default it displays index.js.
You can safely delete your old index.js’s content and paste landing page code there. (Why? Because in NextJS we don’t have to worry about defining the rendering like we do in React)
Next.js uses the
_App component to initialize pages. You can override it and control the page initialization.
Your _App.js should look like :
You can put your old component folder files here and they will run without any changes. For example you created a login page for your website. You had to define it inside App.js in React right? In Next you can simply put it inside pages folder and it automatically creates its routing.
Add your media requirements inside assets.
While putting their address you just have to define it with “/folder/filename” instead of whole path. This is built-in feature inside next. (Life saver for me)
For CSS you can either keep each style in seperate folder for define it globally inside “global.css”.
I personally use both tailwindcss and vanilla css so I use global.css to define any tag.
At last add .next to your .gitignore.
Congrats! You converted your Project to Next.js
For Official Reference you can visit https://nextjs.org/docs/migrating/from-create-react-app
If there is any mistake let me know in comments. Hope you had fun time reading. Cheers!