React Components
24 April 2025 | Category: React Js
Welcome to this beginner-friendly tutorial on React Components! Components are the heart of React, allowing you to build reusable, modular, and maintainable user interfaces. In this guide, you’ll learn what components are, how to create them, and how to use props and state to make them dynamic. We’ll apply these concepts by building a Book Library app that displays a list of books and lets users add new ones. By the end, you’ll be confident creating and combining components to build React applications.
What are React Components?
A React component is a reusable piece of UI, like a button, form, or card, that encapsulates its own structure, style, and behavior. Components can be combined to create complex interfaces, much like LEGO bricks. React supports two main types of components:
1. Functional Components:
- Simple JavaScript functions that return JSX (preferred in modern React).
Example:
const Welcome = () => {
return <h1>Hello, React!</h1>;
};
2. Class Components:
- ES6 classes that extend
React.Component
and include arender
method. They’re used for more complex logic or when legacy code requires them.
Example:
class Welcome extends React.Component {
render() {
return <h1>Hello, React!</h1>;
}
}
Note: We’ll focus on functional components as they’re recommended for new React apps.
Why Use Components?
- Reusability: Write once, use multiple times.
- Modularity: Break complex UIs into manageable pieces.
- Maintainability: Isolate logic and styles for easier updates.
- Scalability: Build large apps by combining small, testable components.
Prerequisites
Before starting, you should have:
- Basic knowledge of React (JSX, ES6) and JavaScript.
- Node.js and npm installed (download from nodejs.org).
- A code editor like Visual Studio Code.
- A terminal for running commands.
We’ll use Create React App to set up our project, which supports JSX, ES6, and React 19 out of the box.
Key Component Concepts
Let’s explore the essential concepts for creating and using React components.
1. Functional Components
Functional components are JavaScript functions that return JSX. They’re simple, concise, and the standard in modern React.
Example:
const Welcome = () => {
return <h1>Hello, React!</h1>;
};
2. Class Components
Class components are ES6 classes that extend React.Component
and include a render
method.
Example:
class Welcome extends React.Component {
render() {
return <h1>Hello, React!</h1>;
}
}
3. Props
Props (short for properties) are read-only inputs passed to components to customize their behavior or appearance.
Example:
const Book = ({ title, author }) => {
return (
<div>
<h2>{title}</h2>
<p>By {author}</p>
</div>
);
};
// Usage
<Book title="React Basics" author="Jane Doe" />
4. State
State is a component’s internal data that can change over time, managed with the useState
hook in functional components.
Example:
const Counter = () => {
const [count, setCount] = React.useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
5. Component Composition
Components can be nested or combined to build complex UIs. A parent component can render child components and pass props to them.
Example:
const App = () => {
return (
<div>
<Book title="React Basics" author="Jane Doe" />
<Book title="JS Advanced" author="John Smith" />
</div>
);
};
Setting Up the Project
Let’s create a React app to build our Book Library, which will use components to display and add books.
- Create a New React App:
- Open your terminal and run:
npx create-react-app book-library cd book-library
- Start the Development Server:
npm start
This opens your app at http://localhost:3000. - Clean Up:
- Open
src/App.js
and replace its content with:
const App = () => { return ( <div> <h1>Book Library</h1> </div> ); }; export default App;
- Delete
src/App.css
,src/logo.svg
, and updatesrc/index.css
with:
body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f5f5f5; } h1 { color: #333; }
- Open
Building the Book Library App
Our Book Library app will:
- Display a list of books using a Book component.
- Allow users to add books via a BookForm component.
- Use state to manage the book list and props to pass data.
- Demonstrate component composition by combining components in App.
Step 1: Create the Book Component
In src
, create a file named Book.js
:
const Book = ({ title, author, year }) => {
return (
<div style={{ backgroundColor: '#fff', padding: '15px', margin: '10px 0', borderRadius: '8px', boxShadow: '0 2px 4px rgba(0, 0, 0, 0.1)', maxWidth: '400px' }}>
<h3>{title}</h3>
<p>Author: {author}</p>
<p>Published: {year}</p>
</div>
);
};
export default Book;
Step 2: Create the BookForm Component
In src
, create a file named BookForm.js
:
const BookForm = ({ onAddBook }) => {
const [title, setTitle] = React.useState('');
const [author, setAuthor] = React.useState('');
const [year, setYear] = React.useState('');
const handleSubmit = (e) => {
e.preventDefault();
if (title.trim() && author.trim() && year.trim()) {
onAddBook({ title, author, year: parseInt(year) });
setTitle('');
setAuthor('');
setYear('');
}
};
return (
<form onSubmit={handleSubmit} style={{ marginBottom: '20px' }}>
<div style={{ marginBottom: '10px' }}>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Book title"
style={{ padding: '8px', width: '200px', borderRadius: '4px' }}
/>
</div>
<div style={{ marginBottom: '10px' }}>
<input
type="text"
value={author}
onChange={(e) => setAuthor(e.target.value)}
placeholder="Author"
style={{ padding: '8px', width: '200px', borderRadius: '4px' }}
/>
</div>
<div style={{ marginBottom: '10px' }}>
<input
type="number"
value={year}
onChange={(e) => setYear(e.target.value)}
placeholder="Publication year"
style={{ padding: '8px', width: '200px', borderRadius: '4px' }}
/>
</div>
<button
type="submit"
style={{ padding: '8px 16px', backgroundColor: '#28a745', color: '#fff', border: 'none', borderRadius: '4px' }}
>
Add Book
</button>
</form>
);
};
export default BookForm;
Step 3: Update the App Component
Update src/App.js
to manage the book list and compose components:
import Book from './Book';
import BookForm from './BookForm';
const App = () => {
const [books, setBooks] = React.useState([
{ title: 'React Guide', author: 'Jane Doe', year: 2023 },
{ title: 'JavaScript Essentials', author: 'John Smith', year: 2021 },
]);
const addBook = (newBook) => {
setBooks([...books, newBook]);
};
return (
<>
<h1>Book Library</h1>
<BookForm onAddBook={addBook} />
<div>
{books.length > 0 ? (
books.map((book, index) => (
<Book key={index} title={book.title} author={book.author} year={book.year} />
))
) : (
<p>No books in the library. Add one!</p>
)}
</div>
</>
);
};
export default App;
Step 4: Test the App
- Save all files and ensure the development server is running (
npm start
). - Open http://localhost:3000. You should see:
- Two initial book cards for “React Guide” and “JavaScript Essentials.”
- A form to add new books with title, author, and year fields.
- New books added to the list when submitted.
Understanding the Code
- Functional Components: Book, BookForm, and App are all functional components, using arrow functions for simplicity.
- Props: The Book component receives title, author, and year as props, while BookForm receives onAddBook to communicate with App.
- State: The App component uses
useState
to manage the book list, and BookForm uses it for form inputs. - Component Composition: App combines BookForm (for input) and multiple Book components (for display), creating a cohesive UI.
- JSX: Each component returns JSX to define its UI, with dynamic rendering via props and state.
Best Practices for Components
- Single Responsibility: Each component should have one job (e.g., Book displays a book, BookForm handles input).
- Reusable Components: Design components to work with different props (e.g., Book works for any book data).
- Keep State Minimal: Store state in the parent component (App) and pass it down via props.
- Unique Keys: Use unique key props in lists (prefer IDs over index for stability).
What’s Next?
- Add Features: Implement a button to delete books or toggle a “read” status.
- Learn Hooks: Explore
useEffect
for fetching data oruseReducer
for complex state. - **Style
the App**: Use CSS or styled-components to improve the UI.
With this foundation, you’re ready to tackle more advanced React concepts like context, custom hooks, and React Router for routing!