javascriptroom guide

Building Your First React App: A Step-by-Step Tutorial

React, developed by Facebook (now Meta), is one of the most popular JavaScript libraries for building user interfaces. It’s known for its simplicity, reusability, and efficiency, making it a top choice for developers creating single-page applications (SPAs) or dynamic web interfaces. If you’re new to React, this tutorial will guide you through building your first React app from scratch. We’ll cover everything from setting up your development environment to deploying your app online. By the end, you’ll have a functional, interactive app and a solid foundation to explore more advanced React concepts.

Table of Contents

  1. Prerequisites
  2. Setting Up Your Development Environment
  3. Creating Your First React App
  4. Understanding the Project Structure
  5. Running the Default App
  6. Modifying the Default App: Hello, React!
  7. Creating a Custom Component
  8. Styling Your React App
  9. Adding Interactivity: State Management with Hooks
  10. Handling User Input with Forms
  11. Deploying Your React App
  12. Conclusion
  13. References

Prerequisites

Before diving in, ensure you have the following tools installed:

  • Basic Knowledge: Familiarity with HTML, CSS, and JavaScript (ES6+ features like arrow functions, const/let).
  • Node.js and npm: React requires Node.js (which includes npm, the Node Package Manager) to run. If you don’t have them installed:
    • Download Node.js from nodejs.org (LTS version recommended).
    • Verify installation by running node -v and npm -v in your terminal (should show version numbers).

Setting Up Your Development Environment

With Node.js installed, we’ll use Create React App (CRA)—an official tool from the React team—to set up a new React project with zero configuration. CRA handles build tools (like Babel and Webpack) so you can focus on coding.

Creating Your First React App

Follow these steps to create your app:

  1. Open your terminal: On Windows, use Command Prompt or PowerShell; on Mac/Linux, use Terminal.

  2. Navigate to your desired folder: Use cd path/to/your/folder to go to the directory where you want to create the app.

  3. Run the CRA command:

    npx create-react-app my-first-react-app  
    • npx is a tool that runs npm packages without installing them globally.
    • my-first-react-app is the name of your project (you can change it, but avoid spaces or special characters).
  4. Wait for setup: CRA will download dependencies and set up the project structure. This may take a minute or two.

Understanding the Project Structure

Once setup is complete, navigate into your project folder:

cd my-first-react-app  

Open the folder in your code editor (e.g., VS Code). You’ll see a structure like this:

my-first-react-app/  
├── node_modules/       # Dependencies (auto-generated)  
├── public/             # Static files  
│   ├── index.html      # HTML template (entry point)  
│   ├── favicon.ico     # Icon for the browser tab  
│   └── ...  
├── src/                # Source code (your app lives here)  
│   ├── App.js          # Main component  
│   ├── App.css         # Styles for App.js  
│   ├── index.js        # Renders the app to the DOM  
│   ├── index.css       # Global styles  
│   ├── logo.svg        # Default React logo  
│   └── ...  
├── .gitignore          # Files Git should ignore  
├── package.json        # Project metadata and scripts  
└── README.md           # Documentation  

Key files to know:

  • public/index.html: The only HTML file in the app. React injects your app into the <div id="root"></div> here.
  • src/index.js: The JavaScript entry point. It imports App.js and renders it into the root div.
  • src/App.js: The main component of your app. This is where you’ll write most of your code initially.

Running the Default App

Let’s see what the default React app looks like:

  1. In your terminal, run:

    npm start  

    This starts a development server. Your app will open automatically in your browser at http://localhost:3000.

  2. You’ll see the default React landing page with a rotating logo and “Learn React” link.

Modifying the Default App

Let’s customize the app to display “Hello, React!” instead of the default content.

Step 1: Edit App.js

Open src/App.js in your editor. The default code looks like this:

import logo from './logo.svg';  
import './App.css';  

function App() {  
  return (  
    <div className="App">  
      <header className="App-header">  
        <img src={logo} className="App-logo" alt="logo" />  
        <p>  
          Edit <code>src/App.js</code> and save to reload.  
        </p>  
        <a  
          className="App-link"  
          href="https://reactjs.org"  
          target="_blank"  
          rel="noopener noreferrer"  
        >  
          Learn React  
        </a>  
      </header>  
    </div>  
  );  
}  

export default App;  

Step 2: Simplify the JSX

Replace the code inside the return statement with a simpler JSX structure:

function App() {  
  return (  
    <div className="App">  
      <h1>Hello, React!</h1>  
      <p>Welcome to my first React app.</p>  
    </div>  
  );  
}  
  • What is JSX? JSX (JavaScript XML) is a syntax extension for JavaScript that lets you write HTML-like code in React. It’s not HTML—under the hood, it’s converted to JavaScript functions (e.g., React.createElement).

Step 3: Remove Unused Imports

Delete the import logo from './logo.svg'; line (we’re no longer using the logo).

Step 4: Save and View Changes

Save App.js. The development server will auto-reload, and your browser will now show:

  • A heading: “Hello, React!”
  • A paragraph: “Welcome to my first React app.”

Creating a Custom Component

React apps are built with components—reusable, self-contained pieces of UI. Let’s create a custom component.

Step 1: Create a Greeting Component

  1. In the src folder, create a new file named Greeting.js.
  2. Add the following code to define a functional component:
// Greeting.js  
function Greeting(props) {  
  return <h2>Hello, {props.name}!</h2>;  
}  

export default Greeting;  
  • Props: props (short for “properties”) let you pass data from a parent component to a child component. Here, props.name will receive a value when we use the Greeting component.

Step 2: Use the Component in App.js

Import Greeting into App.js and use it:

// App.js  
import './App.css';  
import Greeting from './Greeting'; // Import the component  

function App() {  
  return (  
    <div className="App">  
      <h1>Hello, React!</h1>  
      <p>Welcome to my first React app.</p>  
      <Greeting name="Alice" /> {/* Pass a "name" prop */}  
      <Greeting name="Bob" />  
    </div>  
  );  
}  

export default App;  

Save the files. Your browser will now display:

  • “Hello, React!”
  • “Welcome to my first React app.”
  • “Hello, Alice!”
  • “Hello, Bob!”

Styling Your React App

Let’s add some style to make the app look better. We’ll use CSS for simplicity.

Step 1: Edit App.css

Open src/App.css and replace the default styles with:

/* App.css */  
.App {  
  text-align: center;  
  padding: 2rem;  
  font-family: Arial, sans-serif;  
  background-color: #f0f8ff;  
  min-height: 100vh;  
}  

h1 {  
  color: #2c3e50;  
}  

p {  
  color: #34495e;  
  font-size: 1.2rem;  
}  

h2 {  
  color: #e74c3c;  
}  

Step 2: See the Changes

Save App.css. The app will now have a light blue background, centered text, and styled headings/paragraphs.

Adding Interactivity: State Management with Hooks

React apps become dynamic with state—data that can change over time and trigger re-renders. We’ll use the useState hook to add a counter.

What is a Hook?

Hooks are functions that let you “hook into” React state and lifecycle features from functional components. useState is the most basic hook for managing state.

Step 1: Add a Counter to App.js

Update App.js to include a counter:

import './App.css';  
import { useState } from 'react'; // Import useState  

function App() {  
  // Declare a state variable "count" and a setter function "setCount"  
  const [count, setCount] = useState(0);  

  // Function to increment the count  
  const handleIncrement = () => {  
    setCount(count + 1);  
  };  

  return (  
    <div className="App">  
      <h1>Hello, React!</h1>  
      <p>Welcome to my first React app.</p>  
      <p>Counter: {count}</p>  
      <button onClick={handleIncrement}>Increment</button>  
    </div>  
  );  
}  

export default App;  

How It Works:

  • useState(0) initializes the count state to 0.
  • setCount(count + 1) updates the state when the button is clicked.
  • React re-renders the component whenever state changes, so the new count value is displayed.

Test the Counter

Save App.js and click the “Increment” button—the counter will update!

Handling User Input with Forms

Let’s add a form to let users enter their name and display a greeting.

Step 1: Add a Form to App.js

Update App.js with a form input and state:

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

function App() {  
  const [name, setName] = useState(''); // State for the input value  

  // Update state when the user types  
  const handleChange = (e) => {  
    setName(e.target.value);  
  };  

  return (  
    <div className="App">  
      <h1>Hello, React!</h1>  
      <p>Welcome to my first React app.</p>  

      {/* Form input */}  
      <input  
        type="text"  
        placeholder="Enter your name"  
        value={name}  
        onChange={handleChange}  
      />  

      {/* Display greeting if name is entered */}  
      {name && <h2>Hello, {name}!</h2>}  
    </div>  
  );  
}  

export default App;  

How It Works:

  • value={name} binds the input’s value to the name state (controlled component).
  • onChange={handleChange} triggers when the user types, updating name with the input value.
  • {name && <h2>...</h2>} uses short-circuit evaluation to display the greeting only if name is not empty.

Running and Testing the App

  • Development Mode: npm start runs the app in development mode (auto-reloads on changes).
  • Build for Production: When ready to deploy, run npm run build. This creates an optimized build folder with static files.
  • Testing: Run npm test to launch the test runner (CRA includes Jest and React Testing Library).

Deploying Your React App

To share your app with others, deploy the build folder. Here’s how to deploy to Netlify (free and easy):

  1. Run npm run build in your terminal to generate the build folder.
  2. Go to netlify.com and sign up (free).
  3. Click “Add new site” → “Deploy manually”.
  4. Drag and drop the build folder from your project into the Netlify dashboard.

Your app will be deployed instantly! Netlify will give you a URL (e.g., https://your-app-name.netlify.app).

Conclusion

Congratulations! You’ve built your first React app from scratch. You learned:

  • How to set up a React project with Create React App.
  • The basics of JSX and components.
  • State management with the useState hook.
  • Handling user input with forms.
  • Styling and deploying your app.

React is a powerful library, and this is just the beginning. Explore more hooks (e.g., useEffect), routing with React Router, or state management with Redux to take your apps to the next level!

References

Happy coding! 🚀

References


This tutorial was last updated in 2024. Always refer to the official React docs for the latest features.