Back

Start React from 0 without template!

Post 1 description

1

Introduction

Sometimes you want to create a React project from scratch (or you’re asked to do so in a job interview… 🤔), but you don’t know how to start. In this tutorial, you will learn how to create a React project from scratch.

Prerequisites

Before you start, make sure you have installed the following packages:

Creating a project

  1. Create a new directory for your project and navigate to it:
mkdir my-react-app
cd my-react-app
  1. Initialize a new project with Vite:
npm create vite@latest
  1. Give your project a name:
my-first-react-app
  1. Select Vanilla as your project’s base (remember that we’re starting a React project from scratch, without compilers):
vanilla
  1. Select JavaScript (.jsx) or TypeScript (.tsx):
JavaScript

Dependencies

  1. Enter the project that we just created:
cd my-first-react-app
  1. Install the dependencies:
npm install
  1. Install the React plugin needed to work in Vite:
npm install @vitejs/plugin-react -E
  1. And the React dependencies:
npm install react react-dom -E
  1. Now we’re ready to start writing code 💪:
code .

Configuring Vite

  1. Create a configuration file for Vite: vite.config.js

  2. In the Vite configuration to make it work with React in the ‘vite.config.js’ file:

// ⚡ vite.config.js

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
})
Official documentation of @vitejs/plugin-react

Entry point

  1. Now, create the ‘src’ folder and inside it, create a file ‘App.jsx’:
mkdir src
touch src/App.jsx
📁 src
  └──  📄 App.jsx
  1. And add the start of a React component:
// 📁 src/App.jsx

import React from 'react'

function App() {
  return <h1>Hello, world!</h1>
}

export default App
  1. Delete the content of ‘main.js and change the extension of the ‘main.js’ file to ‘main.jsx’

  2. And also in the HTML, change the script that links to the start of your project to ‘main.jsx’:

<!-- 📁 index.html -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="/vite.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite + React</title>
  </head>
  <body>
    <div id="app"></div>
    <script type="module" src="/main.jsx"></script>
    <!-- 👈 Import our main file -->
  </body>
</html>
  1. Import the “createRoot from React-dom and link it with the HTML element with id ‘app’:
// 📁 main.jsx

import ReactDOM from 'react-dom/client'
import App from './src/App.jsx'

const root = ReactDOM.createRoot(document.getElementById('app'))

root.render(<App />) // 👈 Render our component
  1. Now we can run our project:
npm run dev

Extra!

· You can delete files that come with Vite, like ‘counter.js’ or its styles ‘styles.css’.

· It is highly recommended to use a linter like ESLint and a code formatter like Prettier to format your code.

@AlbertLnz