Popular Searches
Popular Course Categories
Popular Courses

Creating a React Application

Creating a React Application

React Project Setup

Creating a React Application

1. Introduction to Creating a React Application

Creating a React application means setting up a project in which React components are used to build an interactive user interface. React is a JavaScript library that helps developers create reusable components, manage application state, display dynamic data, and respond to user interactions.

A React application typically includes JavaScript or JSX files, CSS stylesheets, an HTML entry point, and project configuration files. Developers can use a build tool such as Vite or a React framework to create and run the application.

For beginners learning React fundamentals, Vite provides a straightforward way to create a React project and start development. For production applications requiring features such as server rendering, static generation, or integrated routing, a React framework may be more suitable.

2. Prerequisites for Creating a React Application

Before creating a React application, you should understand the following technologies and tools.

  • HTML: Provides the basic structure of web pages.
  • CSS: Defines the layout, colors, typography, and appearance of the interface.
  • JavaScript: Provides the programming logic used by React components.
  • Node.js: Provides the JavaScript runtime required by common development tools.
  • npm: Manages project packages and executes development scripts.
  • Code editor: Visual Studio Code or another editor can be used to create and edit project files.
  • Web browser: Chrome, Firefox, Edge, or another modern browser can display and test the application.

3. Step 1: Install Node.js and npm

Node.js is required by common React development tools. npm is included with Node.js and is used to install dependencies and run project commands.

  1. Visit the official Node.js website.
  2. Download a suitable supported version for your operating system.
  3. Run the installer and follow the installation instructions.
  4. Open Command Prompt, PowerShell, or a terminal.
  5. Check whether Node.js and npm are installed correctly.
node -v
npm -v

The commands display the installed Node.js and npm versions. If the terminal reports that the commands are not recognized, verify the installation and PATH configuration.

Download Node.js from the Official Website

4. Step 2: Create a New React Project Using Vite

Vite is a build tool that provides a development server and a production build process. It supports React project templates and is a convenient option for learning React application development.

Open your terminal and execute the following command to create a project named my-react-app.

npm create vite@latest my-react-app -- --template react

This command creates a new project using Vite's React template. Depending on your installed Node.js version and package manager, you may be asked to confirm installation or select project options.

Alternative Interactive Method

npm create vite@latest

Follow the prompts to enter a project name, select a framework, and choose the JavaScript React template.

5. Step 3: Navigate to the Project Folder

After creating the project, move into the project directory using the cd command.

cd my-react-app

This command changes the current terminal directory to the newly created React project. Run the remaining project commands from this directory.

6. Step 4: Install Project Dependencies

Dependencies are external packages required by the application. The package.json file describes the project's dependencies and available scripts.

Run the following command inside the project directory.

npm install

npm reads the project configuration and installs the required packages into the node_modules directory. The package-lock.json file records the dependency resolution for consistent installations.

7. Step 5: Open the Project in a Code Editor

After installing dependencies, open the project folder in your preferred code editor. If Visual Studio Code is installed and its command-line utility is available, use the following command.

code .

The dot represents the current directory. The editor should open the React project so that you can examine its files and write components.

8. Understanding the React Project Structure

A new Vite React project contains configuration files, a public directory, and a source directory. The exact structure may vary according to the selected template and installed tools.

my-react-app/
├── node_modules/
├── public/
│   └── vite.svg
├── src/
│   ├── assets/
│   ├── App.css
│   ├── App.jsx
│   ├── index.css
│   └── main.jsx
├── index.html
├── package.json
├── package-lock.json
├── vite.config.js
└── .gitignore

Important Files and Directories

File or Directory Purpose
node_modules/ Contains installed project packages and their dependencies.
public/ Contains static assets served directly by Vite.
src/ Contains application source code and commonly used components and styles.
src/App.jsx Defines the main example application component.
src/App.css Contains styles associated with the example App component.
src/index.css Contains global stylesheet rules.
src/main.jsx Creates the React root and renders the application into the HTML page.
index.html Provides the HTML entry point containing the element where React mounts.
package.json Stores project metadata, dependencies, and npm scripts.
package-lock.json Records the resolved dependency tree used by npm.
vite.config.js Contains Vite configuration when configuration is required.
.gitignore Specifies files and directories Git should normally ignore.

9. Step 6: Understand the main.jsx File

The main.jsx file is the entry point for the React interface in the default Vite React template. It imports React-related functionality, global styles, and the main App component, then renders the application into the HTML document.

Example

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.jsx";

createRoot(document.getElementById("root")).render(
  <StrictMode>
    <App />
  </StrictMode>
);

Explanation

  • StrictMode: Helps identify certain potential problems during development.
  • createRoot: Creates a React root for rendering the application.
  • index.css: Imports the global stylesheet.
  • App: Imports the main application component.
  • document.getElementById("root"): Finds the HTML element where React should render the application.
  • render(): Renders the App component inside the React root.

10. Step 7: Create Your First React Component

Open src/App.jsx and replace the example code with the following component.

function App() {
  return (
    <div>
      <h1>Welcome to React JS</h1>
      <p>My first React application is running.</p>
      <button>Get Started</button>
    </div>
  );
}

export default App;

This component returns JSX that describes a heading, a paragraph, and a button. React renders the component when it is included in the React root.

11. Step 8: Add CSS Styling

Open src/App.css and add the following styles.

#root {
  max-width: 900px;
  margin: 0 auto;
  padding: 32px;
  font-family: Arial, sans-serif;
}
h1 {
  color: #2563eb;
}
p {
  font-size: 18px;
  color: #444;
}
button {
  padding: 10px 18px;
  border: none;
  border-radius: 6px;
  background-color: #2563eb;
  color: white;
  cursor: pointer;
}
button:hover {
  background-color: #1d4ed8;
}

Import the stylesheet into src/App.jsx by adding this line at the top of the file.

import "./App.css";

CSS controls the visual presentation of the component. You can modify the spacing, typography, colors, and layout according to your design requirements.

12. Step 9: Run the React Application

After creating the component and styles, start the Vite development server.

npm run dev

The terminal displays a local development URL, commonly http://localhost:5173/. Open the exact URL displayed in your terminal using your web browser.

The browser should display the heading, paragraph, and button created in App.jsx. When you edit and save supported source files, Vite typically updates the development page automatically.

13. Step 10: Add Interactivity with useState

A React application can respond to user interactions using event handlers and state. The following example makes the button interactive.

import { useState } from "react";
import "./App.css";

function App() {
  const [message, setMessage] = useState("Welcome to React JS");

  return (
    <div>
      <h1>{message}</h1>
      <p>This is my first interactive React application.</p>
      <button onClick={() => setMessage("You clicked the button!")}>
        Click Me
      </button>
    </div>
  );
}

export default App;

Explanation: The useState Hook stores the current message. When the user clicks the button, setMessage updates the state. React then renders the updated heading.

14. Step 11: Understand package.json Scripts

The package.json file contains scripts that can be executed through npm. A typical Vite React project includes scripts similar to the following.

{
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint .",
    "preview": "vite preview"
  }
}

The available scripts can vary depending on the template and project configuration.

Command Purpose
npm run dev Starts the development server.
npm run build Creates an optimized production build.
npm run lint Runs the configured linting tool, if the script exists.
npm run preview Previews the production build locally after building.

15. Step 12: Build the Application for Production

When your application is ready for deployment, create a production build using the following command.

npm run build

Vite generates optimized production files in the dist directory by default. These files can be deployed to a compatible static hosting service or server.

To preview the production build locally, run:

npm run preview

The preview server is intended for checking the built output locally. It is not a replacement for the actual production hosting environment.

16. Common Errors When Creating a React Application

Error Possible Cause Solution
node or npm command not found Node.js is missing or the PATH configuration is incorrect. Install Node.js and reopen the terminal.
Cannot find module A dependency is missing or an import path is incorrect. Run npm install and verify the import path.
Failed to resolve import A file name, package name, or path is incorrect. Check file names, extensions, and package installation.
Port already in use Another process is using the requested development port. Stop the other process or use an available port offered by Vite.
Blank browser page A JavaScript error or incorrect root element may prevent rendering. Check the browser console and terminal for errors.
CSS not applied The stylesheet is not imported or the selectors do not match. Verify the CSS import and class or element names.
State does not update as expected State may be mutated directly or the update logic may be incorrect. Use the state setter and follow React state update practices.
Dependency or version error The installed Node.js version may not meet the tool's requirements. Check the official tool documentation and install a compatible Node.js version.

17. Best Practices for Creating React Applications

  • Use a supported Node.js version compatible with your build tool.
  • Use Vite for straightforward React learning projects, or consider a React framework when the project requires integrated production features.
  • Organize application code into reusable components.
  • Keep component names descriptive and consistent.
  • Separate global CSS from component-specific styles when appropriate.
  • Use props to pass information between components.
  • Use state for values that change through user interaction.
  • Keep secrets and private API credentials out of client-side source code.
  • Handle loading, error, and empty states when retrieving data.
  • Use version control such as Git to track changes.
  • Test the application in different browsers and screen sizes.
  • Run the production build and resolve build errors before deployment.

18. Practical Project: Personal Welcome Page

Create a small React application that displays a welcome message and lets the user enter their name.

Complete App.jsx Example

import { useState } from "react";
import "./App.css";

function App() {
  const [name, setName] = useState("");

  return (
    <div className="welcome-card">
      <h1>Welcome to My React App</h1>
      <label htmlFor="name">Enter your name:</label>
      <input
        id="name"
        type="text"
        value={name}
        onChange={(event) => setName(event.target.value)}
        placeholder="Your name"
      />
      <h2>{name.trim() ? `Hello, ${name}!` : "Hello, Guest!"}</h2>
    </div>
  );
}

export default App;

Complete App.css Example

.welcome-card {
  max-width: 500px;
  margin: 60px auto;
  padding: 24px;
  border-radius: 12px;
  font-family: Arial, sans-serif;
  text-align: center;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
}
.welcome-card input {
  display: block;
  width: 100%;
  box-sizing: border-box;
  margin-top: 12px;
  padding: 12px;
  border: 1px solid #ccc;
  border-radius: 6px;
}
.welcome-card h2 {
  margin-top: 24px;
}

Project Explanation

  1. The useState Hook stores the name entered by the user.
  2. The input value is controlled by React state.
  3. The onChange event updates the name when the user types.
  4. A conditional expression displays a personalized greeting or the default guest greeting.
  5. CSS styles the application as a centered welcome card.

Expected result: The page initially displays "Hello, Guest!". When the user enters a name, the greeting changes to include that name.

19. Frequently Asked Interview Questions

Q1. What is required to create a React application?

Answer: A developer generally needs JavaScript knowledge, Node.js, a package manager, a code editor, and a project setup tool such as Vite or a React framework.

Q2. What is Vite?

Answer: Vite is a build tool that provides a development server and a production build process for modern web applications, including React applications.

Q3. What is the purpose of npm install?

Answer: It installs the dependencies defined by the project configuration and prepares the project to run.

Q4. What is the purpose of main.jsx?

Answer: In a typical Vite React project, main.jsx creates the React root and renders the main application component into the HTML root element.

Q5. What is the purpose of App.jsx?

Answer: App.jsx commonly contains the main application component and may combine other components to form the user interface.

Q6. How do you run a React application created with Vite?

Answer: Run npm install to install dependencies and npm run dev to start the development server.

Q7. How do you create a production build?

Answer: Run npm run build. In a standard Vite project, the production output is generated in the dist directory.

Q8. Is Create React App still the recommended starting tool?

Answer: Create React App has been deprecated. For new projects, consult the official React documentation for current framework recommendations or use a tool such as Vite when starting from scratch for learning purposes.

20. Practice Exercises

  1. Create a React application that displays your name and introduction.
  2. Build a counter with Increase and Decrease buttons.
  3. Create a welcome form that displays the entered name.
  4. Build a product card with a title, price, and description.
  5. Create a simple task list using useState.
  6. Apply CSS to create a responsive layout.
  7. Add a second component and render it inside App.jsx.
  8. Create a production build and inspect the generated dist directory.

21. Conclusion

Creating a React application involves preparing the development environment, creating a project, installing dependencies, understanding the project structure, writing components, adding styles, and running the development server. Once the basic application works, developers can add interactivity with state, build reusable components, connect APIs, and prepare the project for deployment.

Practising these steps will help you develop a strong foundation for building modern React web applications.


22. Learn React JS with JustAcademy

Explore the React JS Training Course to learn React fundamentals, JSX, components, state management, and practical application development.

JustAcademy React JS Training Course

To learn more about the training, use the following link to register for a course demonstration.

Register for React JS Course Demo

23. Official Learning Resources

Use the official React and Vite documentation to explore current project setup instructions and development practices.

Previous Next
whatsapp