Introduction to create-react-app
Create React App is a command-line interface (CLI) tool that helps you quickly create React applications with no build configuration. It sets up your development environment so that you can use the latest JavaScript features, provides a fast development server with hot reloading, and optimizes your app for production.
Prerequisites
Before we get started, make sure you have Node.js and npm installed on your machine. You can download and install them from here.
Installation
Open your terminal and run the following command to install create-react-app globally:
npm install -g create-react-app
Creating a New React App
To create a new React app, run the following command in your terminal:
npx create-react-app my-react-app
This command creates a new directory called my-react-app
and sets up a new React project inside it.
Running the Development Server
Navigate into your newly created project directory:
cd my-react-app
Start the development server by running:
npm start
This will start the development server and open your new React app in your default web browser.
Understanding the Project Structure
After creating a new React app, you’ll see the following project structure:
my-react-app/
├── README.md
├── node_modules/
├── package.json
├── public/
│ ├── index.html
│ └── ...
└── src/
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
└── ...
public/
: Contains the HTML template (index.html
) and other static assets.src/
: Contains the JavaScript files for your React components.package.json
: Defines the dependencies and scripts for your project.
Creating Your First Component
Let’s create a simple React component. Open the src
directory and create a new file called HelloWorld.js
. Add the following code to define your component:
// src/HelloWorld.js
import React from 'react';
function HelloWorld() {
return <h1>Hello, World!</h1>;
}
export default HelloWorld;
Now, let’s use this component in the App.js
file:
// src/App.js
import React from 'react';
import './App.css';
import HelloWorld from './HelloWorld';
function App() {
return (
<div className="App">
<header className="App-header">
<HelloWorld />
</header>
</div>
);
}
export default App;
Running Your App
After creating your component, save your files and go back to your terminal. Make sure your development server is still running (npm start
). You should see your new component rendered in your browser.
Conclusion
You’ve successfully created a new React app using create-react-app, created a new component, and rendered it in your app. This is just the beginning of your journey with React.