MODULE 4
React Fundamentals
Master the core concepts every React developer needs to know
JSX: JavaScript XML
JSX allows you to write HTML-like code in JavaScript. It's the syntax that makes React so readable.
What is JSX?
// JSX const element =Hello, World!
; // What it becomes (JavaScript) const element = React.createElement('h1', null, 'Hello, World!');
JSX looks like HTML but it's actually JavaScript. The browser doesn't understand JSX directly—it gets compiled to JavaScript function calls.
JSX Rules
- One root element: Wrap multiple elements in a fragment or div
- Close all tags: Even self-closing tags like
- className instead of class: Because
classis a reserved keyword - Use camelCase for attributes:
onClick,onChange, notonclick
JSX Examples
// ✅ Valid JSX const greeting =Hello
; const card = (); const image =Title
Description
; const button = ( );
// ❌ Invalid JSX const invalid =Hello
World
; // Two root elements const image =; // Not self-closed
Embedding Expressions in JSX
Use curly braces {} to embed JavaScript expressions:
const name = "Alice"; const age = 25; const greeting =Hello, {name}! You are {age} years old.
; const calculation =2 + 2 = {2 + 2}
; const conditional ={name.length > 5 ? "Long name" : "Short name"}
;
Functional Components
Components are JavaScript functions that return JSX.
Simple Function Component
function Greeting() {
return Hello, React!
;
}
// Or with arrow function
const Greeting = () => {
return Hello, React!
;
};Component with Parameters
Components receive data through props (properties):
function Welcome(props) {
return Hello, {props.name}!
;
}
// Usage
Destructuring Props
Extract props directly in function parameters:
function Welcome({ name, age }) {
return (
Hello, {name}!
You are {age} years old.
);
}
// Usage
Props (Properties)
Props are how parent components pass data to child components. They're read-only.
Passing Props
function App() {
return (
);
}
function User({ name, role }) {
return {name} is a {role}
;
}Props with Objects
function Profile({ user }) {
return (
{user.name}
Email: {user.email}
City: {user.city}
);
}
const user = { name: "Alice", email: "alice@example.com", city: "NYC" };
Props with Children
Components can contain child elements passed as a special prop:
function Card({ children, title }) {
return (
{title}
{children}
);
}
// Usage
This is the card content
Rendering & Re-rendering
Initial Render
When a component first appears on the page:
// This component renders once when the app starts
function App() {
return Hello!
;
}Re-rendering
A component re-renders when:
- Its props change
- Its state changes (we'll learn about this in Module 5)
- Its parent component re-renders
Re-rendering Example
function Parent() {
return (
);
}
function Child({ message }) {
console.log("Child rendered!");
return {message}
;
}
// When Parent renders, Child also renders
// When message prop changes, Child re-rendersComponent Composition
Build complex UIs by combining simple components:
Example: Building a Blog Post
function BlogPost({ title, author, date, content }) {
return (
);
}
function Header({ title, author, date }) {
return (
{title}
By {author} on {date}
);
}
function Content({ text }) {
return {text}
;
}
function Footer({ author }) {
return Written by {author}
;
}Fragments
Return multiple elements without a wrapper div:
Problem: Extra Div
// This adds an unnecessary div
function List() {
return (
Items
- Item 1
);
}Solution: Fragment
// No extra wrapper
function List() {
return (
<>
Items
- Item 1
Items
- Item 1
Conditional Rendering
if/else (Outside JSX)
function LoginButton({ isLoggedIn }) {
if (isLoggedIn) {
return ;
} else {
return ;
}
}Ternary Operator
Use inside JSX for simple conditions:
function UserGreeting({ isLoggedIn, name }) {
return (
{isLoggedIn ? (
Welcome back, {name}!
) : (
Please log in.
)}
);
}Logical AND (&&)
Render only if condition is true:
function UserGreeting({ isLoggedIn, name }) {
return (
{isLoggedIn && Welcome, {name}!
}
);
}Prevent Rendering with null
function Warning({ shouldShow }) {
if (!shouldShow) {
return null; // Don't render anything
}
return This is a warning!
;
}Lists & Keys
Rendering Lists
Use map() to transform array data into components:
function UserList() {
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" }
];
return (
-
{users.map(user => (
- {user.name} ))}
Why Keys Matter
Keys help React identify which items have changed. Always use unique keys:
// ❌ Bad: Using index as key
{items.map((item, index) => )}
// ✅ Good: Using unique ID
{items.map(item => )}Rendering Nested Data
function PostList() {
const posts = [
{
id: 1,
title: "First Post",
comments: [
{ id: 1, text: "Great!" },
{ id: 2, text: "Thanks!" }
]
},
{
id: 2,
title: "Second Post",
comments: [
{ id: 3, text: "Nice post" }
]
}
];
return (
{posts.map(post => (
{post.title}
{post.comments.map(comment => (
- {comment.text}
))}
))}
);
}Common Patterns
Conditional Component
function Status({ status }) {
switch(status) {
case "loading":
return Loading...
;
case "success":
return Success!
;
case "error":
return Error occurred
;
default:
return Unknown status
;
}
}Default Props
function Button({ label = "Click me", disabled = false }) {
return ;
}
// Usage
// Uses defaults
Key Takeaways
- JSX is JavaScript with HTML-like syntax
- Components are functions that return JSX
- Props are how components receive data
- Conditional rendering controls what displays
- Use
map()and keys to render lists - Compose components together to build complex UIs
- Use fragments to avoid extra wrapper elements
- Keys are crucial for correct list rendering
Practice Exercise
- Create a
Cardcomponent that accepts title and description props - Create a list of cards using an array of data
- Add conditional rendering to show/hide content
- Use fragments to return multiple elements
;
const button = (
);