Introduction to React: Your First Component
Learn the fundamentals of React - what it is, why it exists, and how to create your very first component.
Topics Covered:
Prerequisites:
- Basic JavaScript knowledge
- HTML & CSS basics
Video Tutorial
Overview
React is a JavaScript library for building user interfaces. It lets you create reusable UI components and efficiently update them when your data changes. Created by Facebook (now Meta), React has become one of the most popular frontend frameworks, powering applications like Facebook, Instagram, Netflix, and many others. React's core philosophy is based on declarative programming - you describe what the UI should look like for any given state, and React takes care of efficiently updating the DOM when that state changes.
What is React and Why Use It?
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. Instead of manually manipulating the DOM (like with vanilla JavaScript or jQuery), you describe what the UI should look like, and React efficiently updates it when your data changes. Key Advantages: • Component-Based Architecture: Break your UI into reusable, independent pieces • Declarative Syntax: Write what you want, not how to do it • Virtual DOM: React creates a virtual representation of the DOM for efficient updates • One-Way Data Flow: Data flows down from parent to child, making debugging easier • Rich Ecosystem: Massive community and library ecosystem • Learn Once, Write Anywhere: Works on web, mobile (React Native), and desktop (Electron)
Setting Up a React Project
To start building with React, you need a development environment. The easiest way is using Create React App or a modern framework like Next.js (which this tutorial is built with). Common Setup Options: • Create React App: `npx create-react-app my-app` • Vite: `npm create vite@latest my-app -- --template react` • Next.js: `npx create-next-app@latest` Once set up, you'll have a project structure with components, a package.json file, and a development server that hot-reloads your changes.
Creating Your First Component
Components are the building blocks of React applications. They let you split the UI into independent, reusable pieces. Think of components like JavaScript functions - they accept inputs (called props) and return React elements describing what should appear on screen. There are two ways to write components: 1. Function Components (modern, recommended) 2. Class Components (older, still supported but rarely used) Function components are simpler and more modern. They're just JavaScript functions that return JSX.
// Simple function component
function Welcome() {
return <h1>Hello, World!</h1>;
}
// Using the component (JSX syntax)
function App() {
return (
<div>
<Welcome />
<Welcome />
<Welcome />
</div>
);
}
// Components can be arrow functions too
const Greeting = () => {
return <p>Hello from an arrow function component!</p>;
};
// Components can be exported for use in other files
export function Header() {
return <header>My App Header</header>;
}This shows different ways to create components. Notice how <Welcome /> is used like an HTML tag. Components can be used multiple times. The function name should be PascalCase (capitalized) to distinguish components from regular HTML elements.
Understanding JSX Syntax
JSX is a syntax extension for JavaScript that looks similar to HTML. It allows you to write HTML-like code in your JavaScript files. JSX gets transformed into React.createElement() calls, which create React elements. Key JSX Rules: • Must return a single root element (or use React Fragments) • Use className instead of class • Use camelCase for attributes (onClick, not onclick) • Self-closing tags must have a closing slash • JavaScript expressions go inside curly braces {}
// Basic JSX with JavaScript expressions
const name = "Alice";
const element = <h1>Hello, {name}!</h1>;
// Multiple expressions
const user = { firstName: "John", lastName: "Doe" };
const greeting = (
<div>
<p>Hello, {user.firstName} {user.lastName}!</p>
<p>Current time: {new Date().toLocaleTimeString()}</p>
<p>2 + 2 = {2 + 2}</p>
</div>
);
// Conditional rendering in JSX
const isLoggedIn = true;
const message = (
<div>
{isLoggedIn ? (
<h1>Welcome back!</h1>
) : (
<h1>Please log in.</h1>
)}
</div>
);
// Using fragments to avoid extra div
const Fragment = (
<>
<h1>Title</h1>
<p>Content</p>
</>
);JSX allows you to embed JavaScript expressions inside curly braces. You can use variables, function calls, calculations, and even conditional logic. Fragments (<></>) let you group elements without adding extra DOM nodes.
JSX vs HTML: Key Differences
While JSX looks like HTML, there are important differences you must remember: • className instead of class: HTML uses 'class', JSX uses 'className' • camelCase attributes: onClick, onChange, htmlFor (not onclick, onchange, for) • Self-closing tags: <img /> and <input /> must be self-closing • Inline styles: Must be objects, not strings • Comments: Use {/* comment */} inside JSX
// ❌ WRONG - HTML style
<div class="container" onclick="handleClick()">
<img src="image.jpg">
<input type="text">
</div>
// ✅ CORRECT - JSX style
<div className="container" onClick={handleClick}>
<img src="image.jpg" />
<input type="text" />
</div>
// Inline styles are objects in JSX
const style = { color: 'blue', fontSize: '16px' };
<div style={style}>Styled text</div>
// Or inline
<div style={{ color: 'blue', padding: '10px' }}>
Inline styled element
</div>
// Comments in JSX
<div>
{/* This is a comment */}
<p>Visible content</p>
</div>These differences are important. Forgetting className vs class is a common mistake. The style attribute takes an object with camelCase properties, not CSS strings.
Rendering Components
To display React components on the page, you need to render them. In a React application, you typically render your root component into a DOM element using ReactDOM.render() or createRoot() (React 18+). The rendering process: 1. React calls your component function 2. Component returns JSX 3. React converts JSX to React elements 4. React efficiently updates the DOM 5. Browser displays the result
// In your index.js or main entry point
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
// React 18+ way (recommended)
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
// Older way (React 17 and below)
ReactDOM.render(<App />, document.getElementById('root'));
// Your App component
function App() {
return (
<div>
<h1>My React App</h1>
<Welcome />
</div>
);
}
function Welcome() {
return <h2>Welcome to React!</h2>;
}The root.render() method tells React to render your App component into the DOM element with id='root'. React then handles all updates efficiently using its Virtual DOM.
Common Pitfalls and Best Practices
As you start with React, avoid these common mistakes: Common Mistakes: • Forgetting to return JSX from component • Using 'class' instead of 'className' • Not capitalizing component names • Trying to modify props directly • Not providing keys in lists Best Practices: • Keep components small and focused • Use descriptive component names • Extract repeated logic into reusable components • Follow the single responsibility principle
// ❌ WRONG - No return statement
function BadComponent() {
<h1>This won't work!</h1>
}
// ✅ CORRECT - Has return
function GoodComponent() {
return <h1>This works!</h1>;
}
// ❌ WRONG - Component name not capitalized
function myComponent() {
return <div>Bad</div>;
}
// ✅ CORRECT - PascalCase component name
function MyComponent() {
return <div>Good</div>;
}
// ❌ WRONG - Trying to modify props
function Bad(props) {
props.name = "Changed"; // Don't do this!
return <p>{props.name}</p>;
}
// ✅ CORRECT - Props are read-only
function Good({ name }) {
return <p>{name}</p>;
}Remember: components must return JSX, component names must be capitalized, and props are immutable. Following these rules prevents many common bugs.
Conclusion
Congratulations! You've created your first React component. Components are the foundation of React applications - they encapsulate UI and logic together.