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:
1// File: WelcomeMessage.jsx
2import React from 'react';
3
4function WelcomeMessage() {
5 return (
6 <div className="welcome-container">
7 <h1>Welcome to the world of React!</h1>
8 <p>This is your first component.</p>
9 </div>
10 );
11}
12
13export 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:
1// With JSX
2function WelcomeMessage() {
3 return (
4 <div className="welcome-container">
5 <h1>Welcome to the world of React!</h1>
6 <p>This is your first component.</p>
7 </div>
8 );
9}
10
11// Without JSX (this is what React actually transforms JSX into)
12function WelcomeMessage() {
13 return React.createElement(
14 'div',
15 { className: 'welcome-container' },
16 React.createElement('h1', null, 'Welcome to the world of React!'),
17 React.createElement('p', null, 'This is your first component.')
18 );
19}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:
1// File: WelcomeMessage.jsx
2function WelcomeMessage(props) {
3 return (
4 <div className="welcome-container">
5 <h1>Welcome, {props.name}!</h1>
6 <p>{props.message}</p>
7 </div>
8 );
9}
10
11export default WelcomeMessage;
12
13// Using the component
14<WelcomeMessage name="Cosmonaut" message="Ready for a journey through the React galaxy?" />We can also use props destructuring, which makes the code more readable:
1function WelcomeMessage({ name, message }) {
2 return (
3 <div className="welcome-container">
4 <h1>Welcome, {name}!</h1>
5 <p>{message}</p>
6 </div>
7 );
8}Conditional rendering
One of the strengths of React components is the ability to render different elements depending on certain conditions:
1function WelcomeMessage({ name, isLoggedIn }) {
2 return (
3 <div className="welcome-container">
4 {isLoggedIn ? (
5 <h1>Welcome back, {name}!</h1>
6 ) : (
7 <h1>Welcome, guest! Log in to continue.</h1>
8 )}
9 </div>
10 );
11}Rendering lists
React components are great for rendering lists of data:
1function AstronautList({ astronauts }) {
2 return (
3 <div className="astronaut-list">
4 <h2>Space mission crew:</h2>
5 <ul>
6 {astronauts.map(astronaut => (
7 <li key={astronaut.id}>
8 {astronaut.name} - {astronaut.role}
9 </li>
10 ))}
11 </ul>
12 </div>
13 );
14}
15
16// Usage
17const crewMembers = [
18 { id: 1, name: "John Smith", role: "Captain" },
19 { id: 2, name: "Anna Green", role: "Scientist" },
20 { id: 3, name: "Thomas Wright", role: "Engineer" }
21];
22
23<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
1// WelcomeMessage.css
2.welcome-container {
3 padding: 20px;
4 border-radius: 8px;
5 background-color: #f5f5f5;
6 text-align: center;
7}
8
9// WelcomeMessage.jsx
10import React from 'react';
11import './WelcomeMessage.css';
12
13function WelcomeMessage({ name }) {
14 return (
15 <div className="welcome-container">
16 <h1>Welcome, {name}!</h1>
17 </div>
18 );
19}2. Inline styles
1function WelcomeMessage({ name }) {
2 const styles = {
3 container: {
4 padding: '20px',
5 borderRadius: '8px',
6 backgroundColor: '#f5f5f5',
7 textAlign: 'center'
8 },
9 heading: {
10 color: '#333',
11 fontSize: '24px'
12 }
13 };
14
15 return (
16 <div style={styles.container}>
17 <h1 style={styles.heading}>Welcome, {name}!</h1>
18 </div>
19 );
20}3. CSS Modules
1// WelcomeMessage.module.css
2.container {
3 padding: 20px;
4 border-radius: 8px;
5 background-color: #f5f5f5;
6 text-align: center;
7}
8
9// WelcomeMessage.jsx
10import React from 'react';
11import styles from './WelcomeMessage.module.css';
12
13function WelcomeMessage({ name }) {
14 return (
15 <div className={styles.container}>
16 <h1>Welcome, {name}!</h1>
17 </div>
18 );
19}Component composition
One of the greatest advantages of React is the ability to compose larger interfaces from smaller components:
1// Button.jsx
2function Button({ onClick, children, color = 'blue' }) {
3 return (
4 <button
5 onClick={onClick}
6 style={{
7 backgroundColor: color,
8 color: 'white',
9 padding: '10px 15px',
10 border: 'none',
11 borderRadius: '4px',
12 cursor: 'pointer'
13 }}
14 >
15 {children}
16 </button>
17 );
18}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
1import React, { useState } from 'react';
2
3// Example of a functional component
4function SpaceshipCard({ name, type, speed, crew, status }) {
5 const statusColors = {
6 active: '#4caf50',
7 maintenance: '#ff9800',
8 docked: '#2196f3'
9 };
10
11 return (
12 <div style={{
13 backgroundColor: '#1a1a2e',
14 border: '2px solid #16213e',
15 borderRadius: '12px',
16 padding: '20px',
17 color: 'white',
18 transition: 'transform 0.2s',
19 }}>
20 <div style={{
21 display: 'flex',
22 justifyContent: 'space-between',
23 alignItems: 'center',
24 marginBottom: '15px'
25 }}>
26 <h3 style={{ margin: 0, color: '#00d4ff' }}>{name}</h3>
27 <span style={{
28 padding: '4px 12px',
29 backgroundColor: statusColors[status],
30 borderRadius: '20px',
31 fontSize: '12px',
32 fontWeight: 'bold'
33 }}>
34 {status.toUpperCase()}
35 </span>
36 </div>
37 <div style={{ display: 'grid', gap: '10px' }}>
38 <div style={{ display: 'flex', justifyContent: 'space-between' }}>
39 <span style={{ color: '#888' }}>Type:</span>
40 <span>{type}</span>
41 </div>
42 <div style={{ display: 'flex', justifyContent: 'space-between' }}>
43 <span style={{ color: '#888' }}>Speed:</span>
44 <span>{speed} km/s</span>
45 </div>
46 <div style={{ display: 'flex', justifyContent: 'space-between' }}>
47 <span style={{ color: '#888' }}>Crew:</span>
48 <span>{crew} people</span>
49 </div>
50 </div>
51 </div>
52 );
53}
54
55// Component with props and children
56function SpaceSection({ title, children }) {
57 return (
58 <section style={{
59 backgroundColor: '#0f0f23',
60 borderRadius: '16px',
61 padding: '25px',
62 marginBottom: '20px'
63 }}>
64 <h2 style={{
65 color: '#00d4ff',
66 borderBottom: '2px solid #16213e',
67 paddingBottom: '10px',
68 marginTop: 0
69 }}>
70 {title}
71 </h2>
72 {children}
73 </section>
74 );
75}
76
77// Main application component
78export default function App() {
79 const [selectedShip, setSelectedShip] = useState(null);
80
81 const spaceships = [
82 { id: 1, name: 'Aurora', type: 'Research ship', speed: 50000, crew: 12, status: 'active' },
83 { id: 2, name: 'Nebula', type: 'Transport ship', speed: 35000, crew: 8, status: 'docked' },
84 { id: 3, name: 'Phoenix', type: 'Combat ship', speed: 75000, crew: 25, status: 'maintenance' },
85 { id: 4, name: 'Odyssey', type: 'Colonization ship', speed: 20000, crew: 500, status: 'active' },
86 ];
87
88 return (
89 <div style={{
90 fontFamily: 'Arial, sans-serif',
91 backgroundColor: '#0a0a1a',
92 minHeight: '100vh',
93 padding: '20px',
94 color: 'white'
95 }}>
96 <header style={{
97 textAlign: 'center',
98 marginBottom: '30px',
99 padding: '30px',
100 background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
101 borderRadius: '16px'
102 }}>
103 <h1 style={{ margin: 0, fontSize: '2.5rem' }}>Space Fleet</h1>
104 <p style={{ margin: '10px 0 0 0', opacity: 0.9 }}>
105 Manage spaceships using React components
106 </p>
107 </header>
108
109 <SpaceSection title="Ships in the system">
110 <div style={{
111 display: 'grid',
112 gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))',
113 gap: '20px'
114 }}>
115 {spaceships.map(ship => (
116 <div key={ship.id} onClick={() => setSelectedShip(ship)}>
117 <SpaceshipCard {...ship} />
118 </div>
119 ))}
120 </div>
121 </SpaceSection>
122
123 {selectedShip && (
124 <SpaceSection title="Selected ship details">
125 <div style={{
126 backgroundColor: '#1a1a2e',
127 padding: '20px',
128 borderRadius: '12px'
129 }}>
130 <h3 style={{ color: '#00d4ff', marginTop: 0 }}>{selectedShip.name}</h3>
131 <p>This ship of type "{selectedShip.type}" can hold {selectedShip.crew} crew members.</p>
132 <p>Maximum speed: {selectedShip.speed.toLocaleString()} km/s</p>
133 <button
134 onClick={() => setSelectedShip(null)}
135 style={{
136 padding: '10px 20px',
137 backgroundColor: '#f44336',
138 color: 'white',
139 border: 'none',
140 borderRadius: '8px',
141 cursor: 'pointer'
142 }}
143 >
144 Close
145 </button>
146 </div>
147 </SpaceSection>
148 )}
149
150 <div style={{
151 backgroundColor: '#1a1a2e',
152 padding: '20px',
153 borderRadius: '12px',
154 marginTop: '20px'
155 }}>
156 <h3 style={{ color: '#4caf50', marginTop: 0 }}>Key component concepts:</h3>
157 <ul style={{ lineHeight: '1.8', color: '#ccc' }}>
158 <li><strong>Props</strong> - data passed to a component (name, type, speed...)</li>
159 <li><strong>Children</strong> - content between a component's tags</li>
160 <li><strong>Composition</strong> - components can contain other components</li>
161 <li><strong>Reusability</strong> - SpaceshipCard used multiple times with different data</li>
162 </ul>
163 </div>
164 </div>
165 );
166}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.