JavaScript and React course ยท Module 1: React Basics
Your first component
In this lesson10
At the heart of React are components - self-contained, reusable blocks of code that encapsulate HTML, CSS, and JavaScript. Components are like LEGO blocks from which you build your user interface. In this lesson, we'll create our first React component and understand its basic structure.
What is a React component?
A React component is a JavaScript function (or class) that returns a React element (JSX). Components allow you to split the user interface into independent, reusable parts and think about each part separately.
Creating your first functional component
Let's start by creating a simple functional component. A functional component is a regular JavaScript function that returns JSX:
// File: WelcomeMessage.jsx
import React from 'react';
function WelcomeMessage() {
return (
<div className="welcome-container">
<h1>Welcome to the world of React!</h1>
<p>This is your first component.</p>
</div>
);
}
export default WelcomeMessage;Key elements of this component:
- Import React -
import React from 'react';(since React 17 this isn't necessary: the new JSX transform used by Vite adds the required code for you, which is why App.jsx in the Vite template has no such import; you will still see it in older code and in this lesson) - Function declaration -
function WelcomeMessage() {...} - Return with JSX - The function returns JSX that defines the component structure
- Export -
export default WelcomeMessage;allows importing the component in other files
JSX - what is it exactly?
JSX (JavaScript XML) is a syntax extension for JavaScript that allows you to write code resembling HTML directly in JavaScript. Without JSX, creating React elements would be much more complex:
// With JSX
function WelcomeMessage() {
return (
<div className="welcome-container">
<h1>Welcome to the world of React!</h1>
<p>This is your first component.</p>
</div>
);
}
// Without JSX (this is what React actually transforms JSX into)
function WelcomeMessage() {
return React.createElement(
'div',
{ className: 'welcome-container' },
React.createElement('h1', null, 'Welcome to the world of React!'),
React.createElement('p', null, 'This is your first component.')
);
}As you can see, JSX makes the code much more readable and resembles HTML, which most developers are familiar with.
JSX rules
JSX looks like HTML but has several important differences:
classNameinstead ofclass- Since "class" is a reserved keyword in JavaScript, in JSX we useclassNameto define CSS classes- Attributes use camelCase - HTML attributes like
onclickare written asonClickin JSX - Self-closing tags - Tags like
<img>must be closed:<img /> - JavaScript expressions in JSX - You can use JavaScript expressions in curly braces:
{expression}
Using properties (props)
Components can receive data through properties (props). Props are a way to pass data from a parent component to a child component:
// File: WelcomeMessage.jsx
function WelcomeMessage(props) {
return (
<div className="welcome-container">
<h1>Welcome, {props.name}!</h1>
<p>{props.message}</p>
</div>
);
}
export default WelcomeMessage;
// Using the component
<WelcomeMessage name="Cosmonaut" message="Ready for a journey through the React galaxy?" />We can also use props destructuring, which makes the code more readable:
function WelcomeMessage({ name, message }) {
return (
<div className="welcome-container">
<h1>Welcome, {name}!</h1>
<p>{message}</p>
</div>
);
}Conditional rendering
One of the strengths of React components is the ability to render different elements depending on certain conditions:
function WelcomeMessage({ name, isLoggedIn }) {
return (
<div className="welcome-container">
{isLoggedIn ? (
<h1>Welcome back, {name}!</h1>
) : (
<h1>Welcome, guest! Log in to continue.</h1>
)}
</div>
);
}Rendering lists
React components are great for rendering lists of data:
function AstronautList({ astronauts }) {
return (
<div className="astronaut-list">
<h2>Space mission crew:</h2>
<ul>
{astronauts.map(astronaut => (
<li key={astronaut.id}>
{astronaut.name} - {astronaut.role}
</li>
))}
</ul>
</div>
);
}
// Usage
const crewMembers = [
{ id: 1, name: "John Smith", role: "Captain" },
{ id: 2, name: "Anna Green", role: "Scientist" },
{ id: 3, name: "Thomas Wright", role: "Engineer" }
];
<AstronautList astronauts={crewMembers} />Note the key attribute - it is required when rendering lists so that React can efficiently update the DOM when the list changes.
Styling components
There are several ways to style React components:
1. External CSS stylesheet
// WelcomeMessage.css
.welcome-container {
padding: 20px;
border-radius: 8px;
background-color: #f5f5f5;
text-align: center;
}
// WelcomeMessage.jsx
import React from 'react';
import './WelcomeMessage.css';
function WelcomeMessage({ name }) {
return (
<div className="welcome-container">
<h1>Welcome, {name}!</h1>
</div>
);
}2. Inline styles
function WelcomeMessage({ name }) {
const styles = {
container: {
padding: '20px',
borderRadius: '8px',
backgroundColor: '#f5f5f5',
textAlign: 'center'
},
heading: {
color: '#333',
fontSize: '24px'
}
};
return (
<div style={styles.container}>
<h1 style={styles.heading}>Welcome, {name}!</h1>
</div>
);
}3. CSS Modules
// WelcomeMessage.module.css
.container {
padding: 20px;
border-radius: 8px;
background-color: #f5f5f5;
text-align: center;
}
// WelcomeMessage.jsx
import React from 'react';
import styles from './WelcomeMessage.module.css';
function WelcomeMessage({ name }) {
return (
<div className={styles.container}>
<h1>Welcome, {name}!</h1>
</div>
);
}Component composition
One of the greatest advantages of React is the ability to compose larger interfaces from smaller components:
// Button.jsx
function Button({ onClick, children, color = 'blue' }) {
return (
<button
onClick={onClick}
style={{
backgroundColor: color,
color: 'white',
padding: '10px 15px',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
{children}
</button>
);
}Summary
In this lesson we learned:
- What React components are and how to create them
- The basics of JSX and its rules
- How to use props to pass data
- Conditional rendering and lists
- Different methods of styling components
- Component composition for building larger interfaces
Components are the fundamental element of React, and understanding how they work is key to effective React application development. In the following modules, we'll dive deeper into advanced concepts like state, component lifecycle, and hooks.
Code for this lesson: App.jsx
import React, { useState } from 'react';
// Example of a functional component
function SpaceshipCard({ name, type, speed, crew, status }) {
const statusColors = {
active: '#4caf50',
maintenance: '#ff9800',
docked: '#2196f3'
};
return (
<div style={{
backgroundColor: '#1a1a2e',
border: '2px solid #16213e',
borderRadius: '12px',
padding: '20px',
color: 'white',
transition: 'transform 0.2s',
}}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '15px'
}}>
<h3 style={{ margin: 0, color: '#00d4ff' }}>{name}</h3>
<span style={{
padding: '4px 12px',
backgroundColor: statusColors[status],
borderRadius: '20px',
fontSize: '12px',
fontWeight: 'bold'
}}>
{status.toUpperCase()}
</span>
</div>
<div style={{ display: 'grid', gap: '10px' }}>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<span style={{ color: '#888' }}>Type:</span>
<span>{type}</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<span style={{ color: '#888' }}>Speed:</span>
<span>{speed} km/s</span>
</div>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<span style={{ color: '#888' }}>Crew:</span>
<span>{crew} people</span>
</div>
</div>
</div>
);
}
// Component with props and children
function SpaceSection({ title, children }) {
return (
<section style={{
backgroundColor: '#0f0f23',
borderRadius: '16px',
padding: '25px',
marginBottom: '20px'
}}>
<h2 style={{
color: '#00d4ff',
borderBottom: '2px solid #16213e',
paddingBottom: '10px',
marginTop: 0
}}>
{title}
</h2>
{children}
</section>
);
}
// Main application component
export default function App() {
const [selectedShip, setSelectedShip] = useState(null);
const spaceships = [
{ id: 1, name: 'Aurora', type: 'Research ship', speed: 50000, crew: 12, status: 'active' },
{ id: 2, name: 'Nebula', type: 'Transport ship', speed: 35000, crew: 8, status: 'docked' },
{ id: 3, name: 'Phoenix', type: 'Combat ship', speed: 75000, crew: 25, status: 'maintenance' },
{ id: 4, name: 'Odyssey', type: 'Colonization ship', speed: 20000, crew: 500, status: 'active' },
];
return (
<div style={{
fontFamily: 'Arial, sans-serif',
backgroundColor: '#0a0a1a',
minHeight: '100vh',
padding: '20px',
color: 'white'
}}>
<header style={{
textAlign: 'center',
marginBottom: '30px',
padding: '30px',
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
borderRadius: '16px'
}}>
<h1 style={{ margin: 0, fontSize: '2.5rem' }}>Space Fleet</h1>
<p style={{ margin: '10px 0 0 0', opacity: 0.9 }}>
Manage spaceships using React components
</p>
</header>
<SpaceSection title="Ships in the system">
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
gap: '20px'
}}>
{spaceships.map(ship => (
<div key={ship.id} onClick={() => setSelectedShip(ship)}>
<SpaceshipCard {...ship} />
</div>
))}
</div>
</SpaceSection>
{selectedShip && (
<SpaceSection title="Selected ship details">
<div style={{
backgroundColor: '#1a1a2e',
padding: '20px',
borderRadius: '12px'
}}>
<h3 style={{ color: '#00d4ff', marginTop: 0 }}>{selectedShip.name}</h3>
<p>This ship of type "{selectedShip.type}" can hold {selectedShip.crew} crew members.</p>
<p>Maximum speed: {selectedShip.speed.toLocaleString()} km/s</p>
<button
onClick={() => setSelectedShip(null)}
style={{
padding: '10px 20px',
backgroundColor: '#f44336',
color: 'white',
border: 'none',
borderRadius: '8px',
cursor: 'pointer'
}}
>
Close
</button>
</div>
</SpaceSection>
)}
<div style={{
backgroundColor: '#1a1a2e',
padding: '20px',
borderRadius: '12px',
marginTop: '20px'
}}>
<h3 style={{ color: '#4caf50', marginTop: 0 }}>Key component concepts:</h3>
<ul style={{ lineHeight: '1.8', color: '#ccc' }}>
<li><strong>Props</strong> - data passed to a component (name, type, speed...)</li>
<li><strong>Children</strong> - content between a component's tags</li>
<li><strong>Composition</strong> - components can contain other components</li>
<li><strong>Reusability</strong> - SpaceshipCard used multiple times with different data</li>
</ul>
</div>
</div>
);
}Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What letter must a component name start with so that JSX treats <Name /> as a component rather than an HTML tag?
Hands-on tasks in the game
- Horizontal ordering
Arrange the correct default export syntax for a React component:
- Code editor
Create a StationModule component: a function that takes props and returns a <div> with the module name (props.name) and status (props.status). Example: 'Module: Engines | Status: Online'
- Click in order
Arrange the syntax of a functional component:
- Code editor
Create a SpaceCapsule that accepts { missionName, crew, destination }. Display: 'Mission: [missionName]', 'Crew: [crew] members', 'Destination: [destination]'. Use props destructuring.
- Vertical ordering
Arrange the process of creating a React component:
- Code editor
Create a Navigation component in a separate file (e.g. Navigation.jsx) and export it, then import it in App.jsx and render it in the main Spaceship component.