Create Your First React Web Application

React is a JavaScript library for building user interfaces. in this article, we are going to create hello world application with React. This tutorial is only for very beginners. Let’s get started:

Table of Contents

  1. Prerequisites
  2. Create React App
  3. Folder Structure
  4. Change Port Number
  5. Make Component
  6. Use Component
  7. React Developer Tools

Prerequisites

Before getting started with React, you should have basic knowledge of HTML, CSS, JavaScript, DOM, ES6. And Node.js, npm need to be installed globally on your machine.

Create React App

Run the following command to create a react app:

npx create-react-app hello-world

It generates all files, folders, and libraries we need. Now navigate the project folder and start the app:

# go to project folder
cd hello-world

# start app
npm start

We’re able to see the app at http://localhost:3000/.

.env
PORT=3005

Folder Structure

Let’s have a look at the React app folder structure in short.

  • node_modules: All external libraries will be stored here. No need to edit any single line code of this folder.
  • public: This folder contains all static files such as robots.txt, logo, ads.txt etc.
  • src: We’ll do most of the things in this folder.
  • package.json: It contains all metadata information about the application.

Change Port Number

By default the react app runs on port 3000. We can change the port easily. Create a file named .env at the root of the project directory. Then insert this line:

Now the app will run on new port http://localhost:3005/.

Make Component

React lets us define components as classes or functions. Components are reusable bits of code. We can create component in .JSX or .JS file. The component name should be written in Title Case like HelloWorld.

Let’s create our first component named ‘HelloWorld‘ inside src folder:

src/HelloWorld.js
import React from 'react';

const HelloWorld = () => {

  function sayHello() {
    alert('Hello, World!');
  }

  return (
    
  );
};

export default HelloWorld;

This is a simple component. It will show “Hello World” alert on button click.

Use Component

We can import the component in any file. After importing component, we can use it anywhere like:

<ComponentName/>

Let’s use our HelloWorld component. Open src/App.js file and paste these codes:

App.js
import React from 'react';
import HelloWorld from './HelloWorld';
import './App.css';

function App() {
  return (
    <div className="App">
      <HelloWorld />
    </div>
  );
}

export default App;

React has hot reloading feature. App will be reloaded automatically and you’ll see the “Say Hello!” button. Click the button and see the output.

React Developer Tools

React Developer Tools that will make our life much easier when working with React. It allows us to inspect the React component hierarchies. You can add the extension into Chrome, Firefox browser.

That’s it. Thanks for reading.