Table of Contents
- Prerequisites
- Setting Up Your Development Environment
- Creating Your First React App
- Understanding the Project Structure
- Running the Default App
- Modifying the Default App: Hello, React!
- Creating a Custom Component
- Styling Your React App
- Adding Interactivity: State Management with Hooks
- Handling User Input with Forms
- Deploying Your React App
- Conclusion
- 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 -vandnpm -vin 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:
-
Open your terminal: On Windows, use Command Prompt or PowerShell; on Mac/Linux, use Terminal.
-
Navigate to your desired folder: Use
cd path/to/your/folderto go to the directory where you want to create the app. -
Run the CRA command:
npx create-react-app my-first-react-appnpxis a tool that runs npm packages without installing them globally.my-first-react-appis the name of your project (you can change it, but avoid spaces or special characters).
-
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 importsApp.jsand renders it into therootdiv.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:
-
In your terminal, run:
npm startThis starts a development server. Your app will open automatically in your browser at
http://localhost:3000. -
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
- In the
srcfolder, create a new file namedGreeting.js. - 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.namewill receive a value when we use theGreetingcomponent.
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 thecountstate to0.setCount(count + 1)updates the state when the button is clicked.- React re-renders the component whenever state changes, so the new
countvalue 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 thenamestate (controlled component).onChange={handleChange}triggers when the user types, updatingnamewith the input value.{name && <h2>...</h2>}uses short-circuit evaluation to display the greeting only ifnameis not empty.
Running and Testing the App
- Development Mode:
npm startruns the app in development mode (auto-reloads on changes). - Build for Production: When ready to deploy, run
npm run build. This creates an optimizedbuildfolder with static files. - Testing: Run
npm testto 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):
- Run
npm run buildin your terminal to generate thebuildfolder. - Go to netlify.com and sign up (free).
- Click “Add new site” → “Deploy manually”.
- Drag and drop the
buildfolder 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
useStatehook. - 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
- React Official Documentation
- Create React App Docs
- Node.js Download
- Netlify Deployment Guide
- React Hooks Documentation
Happy coding! 🚀
References
- React Official Documentation
- Create React App Docs
- Node.js Download
- Netlify Deployment Guide
- React Hooks Documentation
This tutorial was last updated in 2024. Always refer to the official React docs for the latest features.