How to create your first React App
To create a React application, you will need to have Node.js and a package manager like npm or yarn installed on your machine.
Here are the steps you can follow to create a basic React application:
- Open a terminal and create a new project directory.
mkdir my-project
cd my-project
- Initialize a new npm or yarn project by running the appropriate command:
npm init -y
yarn init -y
This will create a package.json
file in your project directory.
- Install the React library and the React DOM library by running the following command:
npm install react react-dom
yarn add react react-dom
- Create a new file called
index.html
in your project directory and add the following HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>My React App</title>
</head>
<body>
<div id="root"></div>
</body>
</html>
This HTML file will serve as the entry point for your application. The div
element with the id
of root
will be used to mount the React component tree.
- Create a new file called
index.js
in your project directory and add the following code:
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return <div>Hello, World!</div>;
}
ReactDOM.render(<App />, document.getElementById('root'));
This code defines a simple React component called App
that returns a div
element with the text "Hello, World!". It then uses the ReactDOM.render
method to mount the App
component to the div
element with the id
of root
in the index.html
file.
- Open the
index.html
file in a browser to see the "Hello, World!" message.
You can now start building out your React application by adding additional components and functionality. To add additional dependencies, you can use npm or yarn to install them and then import them into your application.