React Hello World
Introduction
Welcome to the world of React! If you're just starting your journey with this popular JavaScript library, you're in the right place. In this tutorial, we'll build your first React application—a simple "Hello World" program. This foundational example will help you understand the basic structure and essential concepts that make React so powerful for building user interfaces.
React is a JavaScript library created by Facebook (now Meta) that's used for building interactive user interfaces. Unlike traditional web development approaches, React uses a component-based architecture that makes it easier to build and maintain complex applications.
Let's dive in and create your first React component!
Prerequisites
Before we begin, you should have:
- Basic knowledge of HTML, CSS, and JavaScript
- Node.js and npm installed on your computer
- A code editor (like VS Code, Sublime Text, or Atom)
Setting Up Your First React Application
There are two main ways to start working with React:
- Using Create React App (recommended for beginners)
- Adding React to an existing HTML page
Let's explore both approaches.
Method 1: Using Create React App
Create React App is an officially supported way to create single-page React applications. It offers a modern build setup with no configuration.
To create a new app, open your terminal and run:
npx create-react-app hello-world
cd hello-world
npm start
This will:
- Create a new directory called
hello-world
- Install all the necessary dependencies
- Set up the build configuration
- Start the development server
Your browser should automatically open to http://localhost:3000/
showing the default React app.
Method 2: Adding React to an HTML Page
For simpler use cases, you can add React directly to an HTML page using script tags:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
// Your React code will go here
</script>
</body>
</html>
Creating Your First React Component
Let's create a simple HelloWorld
component. If you're using Create React App, open src/App.js
and replace its content with:
import React from 'react';
function HelloWorld() {
return (
<div>
<h1>Hello, World!</h1>
<p>Welcome to my first React application</p>
</div>
);
}
export default HelloWorld;
Then, update src/index.js
to:
import React from 'react';
import ReactDOM from 'react-dom/client';
import HelloWorld from './App';
import './index.css';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<HelloWorld />
</React.StrictMode>
);
If you're using the HTML page method, put this inside the script tag:
function HelloWorld() {
return (
<div>
<h1>Hello, World!</h1>
<p>Welcome to my first React application</p>
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<HelloWorld />);
Understanding the Code
Let's break down what's happening in our component:
-
Component Declaration:
jsxfunction HelloWorld() {
// Component code
}This creates a functional component named
HelloWorld
. In React, components are the building blocks of your UI. -
JSX Return Statement:
jsxreturn (
<div>
<h1>Hello, World!</h1>
<p>Welcome to my first React application</p>
</div>
);The component returns JSX (JavaScript XML), which looks like HTML but is actually a syntax extension for JavaScript. JSX lets you write HTML-like code in your JavaScript.
-
Rendering:
jsxconst root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<HelloWorld />);This code finds the HTML element with id "root" and renders your
HelloWorld
component inside it.
JSX: The Heart of React Components
JSX is a crucial part of React development. It allows you to write HTML-like syntax within JavaScript, making your component structure more readable and intuitive.
Key points about JSX:
- It's not HTML, but looks similar
- JSX expressions must have one parent element (that's why we wrap our content in a
<div>
) - JavaScript expressions can be embedded in JSX using curly braces
Let's enhance our component with some dynamic content using JSX:
function HelloWorld() {
const name = "React Beginner";
const currentDate = new Date().toLocaleDateString();
return (
<div>
<h1>Hello, {name}!</h1>
<p>Welcome to my first React application</p>
<p>Today is {currentDate}</p>
</div>
);
}
The curly braces {}
allow us to embed JavaScript expressions directly in our JSX.
Adding Props to Make Components Reusable
One of React's key principles is reusability. Let's modify our component to accept "props" (properties) that make it more flexible:
function HelloWorld(props) {
return (
<div>
<h1>Hello, {props.name}!</h1>
<p>{props.message}</p>
</div>
);
}
// Then we can use it like this:
ReactDOM.createRoot(document.getElementById('root')).render(
<div>
<HelloWorld name="React Beginner" message="Welcome to your first React app!" />
<HelloWorld name="Web Developer" message="React makes UI development fun!" />
</div>
);
Now we can reuse our HelloWorld
component with different content by passing different props.
Adding Basic Styling
Let's add some basic styling to our component. In Create React App, you can modify the src/App.css
file and import it in your component:
import React from 'react';
import './App.css'; // Import the CSS file
function HelloWorld(props) {
return (
<div className="hello-container">
<h1 className="hello-title">Hello, {props.name}!</h1>
<p className="hello-message">{props.message}</p>
</div>
);
}
export default HelloWorld;
Then in App.css
:
.hello-container {
text-align: center;
margin-top: 50px;
padding: 20px;
border-radius: 8px;
background-color: #f5f5f5;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.hello-title {
color: #4a90e2;
}
.hello-message {
color: #333;
font-size: 18px;
}
Note that in React, we use className
instead of class
for CSS classes, since class
is a reserved keyword in JavaScript.
Adding Interaction with Event Handlers
Let's make our Hello World app interactive by adding a button that changes the greeting:
import React, { useState } from 'react';
import './App.css';
function HelloWorld(props) {
const [greeting, setGreeting] = useState(`Hello, ${props.name}!`);
const changeGreeting = () => {
if (greeting === `Hello, ${props.name}!`) {
setGreeting(`Nice to meet you, ${props.name}!`);
} else {
setGreeting(`Hello, ${props.name}!`);
}
};
return (
<div className="hello-container">
<h1 className="hello-title">{greeting}</h1>
<p className="hello-message">{props.message}</p>
<button onClick={changeGreeting} className="hello-button">
Change Greeting
</button>
</div>
);
}
export default HelloWorld;
In this example, we've introduced:
- State - Using the
useState
hook to keep track of the greeting - Event Handler - The
changeGreeting
function that updates our state - Event Binding - Using
onClick
to connect the button to our handler
Component Lifecycle Visualization
React components go through a lifecycle from creation to removal from the DOM. Here's a simplified visualization:
For functional components with hooks, this looks a bit different, but the concept is similar.
Real-World Application Example
Let's create a more practical example - a simple greeting card application:
import React, { useState } from 'react';
import './App.css';
function GreetingCard() {
const [name, setName] = useState('');
const [submittedName, setSubmittedName] = useState('');
const [submitted, setSubmitted] = useState(false);
const handleSubmit = (event) => {
event.preventDefault();
setSubmittedName(name);
setSubmitted(true);
};
const handleReset = () => {
setName('');
setSubmitted(false);
};
return (
<div className="card-container">
{!submitted ? (
<div className="input-container">
<h2>Create Your Greeting</h2>
<form onSubmit={handleSubmit}>
<label htmlFor="name-input">Enter your name:</label>
<input
id="name-input"
type="text"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Your name"
required
/>
<button type="submit" disabled={!name.trim()}>
Generate Greeting
</button>
</form>
</div>
) : (
<div className="greeting-card">
<h1>Hello, {submittedName}!</h1>
<p>Welcome to the wonderful world of React!</p>
<p>This is your personalized greeting card.</p>
<button onClick={handleReset}>Create New Greeting</button>
</div>
)}
</div>
);
}
export default GreetingCard;
This example demonstrates:
- Form handling in React
- Conditional rendering based on state
- Event handling for multiple events
- Two-way data binding with input fields
- User interaction patterns common in real applications
Summary
Congratulations! You've created your first React application and learned several key React concepts:
- Components: The building blocks of React applications
- JSX: The syntax extension that makes writing React components intuitive
- Props: How to make components flexible and reusable
- State: Managing data that changes over time
- Event Handling: Making your application interactive
- Styling: How to add CSS to your React components
- Conditional Rendering: Showing different UI based on conditions
This is just the beginning of your React journey! With these fundamentals, you're ready to start building more complex applications.
Additional Resources and Exercises
To deepen your understanding of React, try these exercises:
- Exercise 1: Modify the HelloWorld component to display the current time and update it every second.
- Exercise 2: Create a counter component with increment and decrement buttons.
- Exercise 3: Enhance the greeting card with options to change the background color or font.
Recommended Resources:
- Official React Documentation
- React Hooks Documentation
- MDN Web Docs on JavaScript
- CSS-Tricks React Guide
Remember, learning React is a journey. Start with these basics, practice regularly, and gradually build more complex applications as you become comfortable with the fundamentals.
Happy coding!
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)