Reusable Components in React JS
Course Topic: Reusable Components
Technology: React JS, JavaScript, JSX, HTML, CSS
Learning Objective: Understand how to create reusable React components, pass data using props, manage component structure, and build maintainable user interfaces with less code duplication.
1. Introduction to Reusable Components
Reusable Components are independent pieces of user interface that can be created once and used multiple times in a React application. They help developers avoid writing the same JSX and functionality repeatedly.
For example, a website may display several buttons, product cards, profile cards, navigation menus, and form fields. Instead of creating separate markup for every button or card, developers can create reusable components and customize them using props.
React components are commonly written as JavaScript functions that return JSX. A component can accept data through props and display different content each time it is rendered.
Example: A Simple Reusable Component
function Welcome() {
return <h2>Welcome to React JS!</h2>;
}
function App() {
return (
<div>
<Welcome />
<Welcome />
<Welcome />
</div>
);
}
export default App;
In this example, the Welcome component is defined once and rendered three times inside App. This demonstrates the basic idea of component reuse.
2. Why Are Reusable Components Important?
Reusable components make React applications easier to develop, understand, test, and maintain. They are especially useful when the same interface pattern appears on multiple pages or in different parts of a project.
- Code reusability: Write a component once and use it in many places.
- Less duplication: Avoid repeating the same JSX and styling.
- Easy maintenance: Update a shared component in one place instead of editing multiple copies.
- Consistency: Keep similar UI elements visually and functionally consistent.
- Better readability: Break complex interfaces into smaller, meaningful parts.
- Scalability: Extend applications by combining existing components with new ones.
- Testability: Test individual components independently.
- Faster development: Build new pages more quickly using existing UI elements.
3. Characteristics of a Good Reusable Component
A good reusable component should be understandable, configurable, and focused on a clear responsibility. It should work in different situations without requiring unnecessary changes to its internal code.
- Single responsibility: The component should have a clear purpose, such as displaying a product or submitting a form.
- Configurable through props: Different values should be passed through props instead of hardcoding every variation.
- Reusable design: The component should be suitable for multiple instances or use cases.
- Readable code: Use meaningful component and prop names.
- Predictable behavior: The same inputs should produce consistent output when the component is designed as a pure component.
- Flexible content: Use the children prop when a component needs to wrap different kinds of JSX.
- Limited dependencies: Avoid making a generic component depend unnecessarily on a specific page or application feature.
4. Creating a Reusable Component Using Props
Props are inputs passed from a parent component to a child component. They allow developers to customize a reusable component without changing its internal implementation.
Example: Reusable Greeting Component
function Greeting({ name }) {
return <h2>Hello, {name}!</h2>;
}
function App() {
return (
<div>
<Greeting name="Amit" />
<Greeting name="Priya" />
<Greeting name="Rahul" />
</div>
);
}
export default App;
Explanation: The Greeting component receives a name prop. Each instance displays a different name, but the component logic remains the same.
Important Points
- Props are passed through JSX attributes.
- String values can be passed using quotation marks.
- Numbers, arrays, objects, Boolean values, and functions can be passed using curly braces.
- Props should be treated as read-only inputs.
- A component can receive multiple props.
5. Creating Reusable Components with Multiple Props
A reusable component can accept multiple props to control its content, appearance, and behavior.
Example: Reusable Product Card
function ProductCard({ name, price, category }) {
return (
<article className="product-card">
<h3>{name}</h3>
<p>Category: {category}</p>
<p>Price: ₹{price}</p>
</article>
);
}
function App() {
return (
<div>
<ProductCard
name="Laptop"
price={55000}
category="Electronics"
/>
<ProductCard
name="Headphones"
price={2500}
category="Accessories"
/>
<ProductCard
name="Keyboard"
price={1500}
category="Computer Accessories"
/>
</div>
);
}
export default App;
Here, ProductCard accepts name, price, and category. It can display many different products without duplicating the card's JSX.
6. Reusable Components with Default Props Values
Sometimes a component may not receive every optional prop. JavaScript parameter defaults allow developers to provide fallback values when a prop is missing or undefined.
Example
function Button({ label = "Click Me", type = "button" }) {
return (
<button type={type}>
{label}
</button>
);
}
function App() {
return (
<div>
<Button />
<Button label="Save" />
<Button label="Submit" type="submit" />
</div>
);
}
export default App;
In this example, the button displays Click Me if the label prop is not provided. The default type is button, which helps avoid accidentally submitting a form when the button is used inside one.
Note: JavaScript parameter defaults apply when a prop is missing or undefined, not when its value is explicitly null.
7. Reusable Components Using the children Prop
The children prop allows a component to display content nested between its opening and closing tags. This is useful when the same wrapper or container must display different content.
Example: Reusable Card Container
function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
}
function App() {
return (
<div>
<Card>
<h2>React JS</h2>
<p>Learn React component development.</p>
</Card>
<Card>
<h2>JavaScript</h2>
<p>Learn modern JavaScript concepts.</p>
</Card>
</div>
);
}
export default App;
The Card component provides a shared container, while its parent supplies the inner content. The component can therefore be reused for different subjects, products, messages, or profile information.
CSS Example
.card {
padding: 20px;
margin: 12px 0;
border: 1px solid #ccc;
border-radius: 8px;
background-color: #f9f9f9;
}
8. Reusable Button Component
Buttons are among the most common reusable components in web applications. A single Button component can support different labels, styles, and click actions.
Example
function Button({ children, onClick, variant = "primary" }) {
return (
<button
className={`button button-${variant}`}
onClick={onClick}
>
{children}
</button>
);
}
function App() {
return (
<div>
<Button onClick={() => alert("Saved successfully!")}>
Save
</Button>
<Button
variant="secondary"
onClick={() => alert("Operation cancelled.")}
>
Cancel
</Button>
</div>
);
}
export default App;
CSS Example
.button {
padding: 10px 18px;
border: none;
border-radius: 5px;
cursor: pointer;
}
.button-primary {
background-color: #2563eb;
color: white;
}
.button-secondary {
background-color: #e5e7eb;
color: #111827;
}
The Button component can be reused throughout an application. Its children provide the label, onClick defines the action, and variant determines the style.
9. Reusable Components for Rendering Lists
React applications often display collections of items, such as products, students, articles, or courses. Developers can create a reusable component for one item and use JavaScript's map method to render a collection of them.
Example: Student List
function StudentCard({ name, course }) {
return (
<article className="student-card">
<h3>{name}</h3>
<p>Course: {course}</p>
</article>
);
}
function StudentList() {
const students = [
{ id: 1, name: "Amit", course: "React JS" },
{ id: 2, name: "Priya", course: "UI/UX Design" },
{ id: 3, name: "Rahul", course: "Web Development" }
];
return (
<section>
<h2>Students</h2>
{students.map((student) => (
<StudentCard
key={student.id}
name={student.name}
course={student.course}
/>
))}
</section>
);
}
export default StudentList;
The StudentCard component is reused for each student. The key prop gives React a stable identifier for each item so that list elements can be matched correctly between renders.
10. Organizing Reusable Components into Separate Files
In small examples, several components can be defined in one file. In larger applications, it is usually helpful to place components in separate files so that code remains organized and easier to maintain.
Suggested Project Structure
src/
components/
Button.jsx
Card.jsx
ProductCard.jsx
Header.jsx
pages/
Home.jsx
Products.jsx
App.jsx
main.jsx
Button.jsx
function Button({ children }) {
return <button>{children}</button>;
}
export default Button;
App.jsx
import Button from "./components/Button";
function App() {
return (
<div>
<h1>Reusable Components</h1>
<Button>Get Started</Button>
<Button>Learn More</Button>
</div>
);
}
export default App;
The Button component is exported from its own file and imported wherever it is needed. This makes it easier to reuse the component across multiple pages.
Note: Import paths and file extensions should match the project's tooling and file structure.
11. Reusable Components with Conditional Rendering
Conditional rendering allows a component to display different content depending on props or application state. This makes reusable components suitable for situations that require different messages or visual states.
Example: Status Message
function StatusMessage({ isSuccess }) {
return (
<p>
{isSuccess
? "Operation completed successfully."
: "Something went wrong."}
</p>
);
}
function App() {
return (
<div>
<StatusMessage isSuccess={true} />
<StatusMessage isSuccess={false} />
</div>
);
}
export default App;
The same component displays different messages based on the isSuccess prop. This pattern is useful for alerts, loading messages, validation results, and empty states.
12. Reusable Components and Separation of Concerns
Separation of concerns means dividing an application into parts with clearly defined responsibilities. Reusable components help achieve this by keeping individual interface elements separate from the larger page structure.
| Component |
Responsibility |
| Header |
Displays the website title or brand. |
| Button |
Displays a clickable button. |
| ProductCard |
Displays information about one product. |
| ProductList |
Organizes and displays multiple product cards. |
| SearchBar |
Provides a reusable search input interface. |
| Footer |
Displays copyright or supporting links. |
| App |
Combines components into the main application interface. |
This structure makes individual components easier to update without rewriting the entire page.
13. Reusable Components vs. Non-Reusable Code
| Reusable Components |
Repeated Non-Reusable Code |
| Defines shared UI once. |
Repeats similar markup in multiple places. |
| Can be customized through props. |
Often requires editing each repeated section separately. |
| Improves consistency across the application. |
May result in inconsistent styling or behavior. |
| Usually simplifies maintenance. |
Increases maintenance effort as duplication grows. |
| Encourages modular application structure. |
Can lead to large and difficult-to-manage components. |
Example of Repeated Code
function App() {
return (
<div>
<button>Save</button>
<button>Cancel</button>
<button>Continue</button>
</div>
);
}
Improved Reusable Version
function Button({ label }) {
return <button>{label}</button>;
}
function App() {
return (
<div>
<Button label="Save" />
<Button label="Cancel" />
<Button label="Continue" />
</div>
);
}
The second version defines a shared component and uses it with different labels. For simple markup, either approach can be reasonable, but a reusable component becomes more valuable when shared styling, behavior, or structure needs to be maintained across many locations.
14. Common Mistakes When Creating Reusable Components
| Mistake |
Problem |
Solution |
| Hardcoding content |
The component cannot easily display different data. |
Pass variable content through props. |
| Changing props directly |
Props are read-only inputs. |
Use state for values that need to change. |
| Using lowercase component names |
JSX may treat the name as an HTML element. |
Start custom component names with an uppercase letter. |
| Creating overly complicated components |
Components become difficult to understand and maintain. |
Separate clear responsibilities into smaller components. |
| Passing too many unrelated props |
The component becomes difficult to configure. |
Review its responsibility and consider simpler APIs or composition. |
| Forgetting keys in mapped lists |
React may warn about missing list keys. |
Provide stable, unique keys for list items. |
| Defining components inside other components |
Nested component definitions can cause state resets and unnecessary work. |
Define reusable components at the top level of the module. |
| Making every element a component |
Excessive abstraction can make code harder to follow. |
Create components when reuse, clarity, or a distinct responsibility justifies them. |
15. Practical Project: Build a Reusable Product Catalogue
Project Objective: Create a product catalogue using reusable React components.
Project Requirements
- Create a ProductCard component.
- Pass product name, price, and category through props.
- Create a ProductList component to render several products.
- Create a reusable Button component for product actions.
- Use stable keys for the product list.
- Apply CSS to give the cards a consistent appearance.
ProductCard.jsx
function ProductCard({ product }) {
return (
<article className="product-card">
<h3>{product.name}</h3>
<p>Category: {product.category}</p>
<p>Price: ₹{product.price}</p>
<button type="button">View Product</button>
</article>
);
}
export default ProductCard;
ProductList.jsx
import ProductCard from "./ProductCard";
function ProductList() {
const products = [
{ id: 1, name: "Laptop", category: "Electronics", price: 55000 },
{ id: 2, name: "Headphones", category: "Accessories", price: 2500 },
{ id: 3, name: "Keyboard", category: "Computer Accessories", price: 1500 }
];
return (
<section className="product-list">
{products.map((product) => (
<ProductCard key={product.id} product={product} />
))}
</section>
);
}
export default ProductList;
App.jsx
import ProductList from "./ProductList";
function App() {
return (
<main>
<h1>Product Catalogue</h1>
<ProductList />
</main>
);
}
export default App;
CSS Styling
.product-list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 16px;
}
.product-card {
padding: 18px;
border: 1px solid #ddd;
border-radius: 8px;
}
.product-card button {
padding: 8px 12px;
cursor: pointer;
}
Expected Result
The page displays multiple product cards using the same reusable ProductCard component. Each card displays different product information, while the overall layout and styling remain consistent.
Possible Enhancements
- Add product images and descriptions.
- Add a search field to filter products.
- Add category-based filtering.
- Create a reusable badge for product availability.
- Pass click handlers to buttons through props.
- Fetch product data from an API.
16. Best Practices for Reusable Components
- Give every component a clear and meaningful name.
- Use props to customize content and behavior.
- Keep components focused on a specific responsibility.
- Use children when a component should wrap flexible content.
- Define reusable components outside other component functions.
- Use default values for optional props when appropriate.
- Use stable keys when rendering lists of components.
- Keep shared styles consistent and easy to maintain.
- Avoid unnecessary abstractions and overly complicated prop interfaces.
- Test important components with different valid prop values.
- Keep interactive behavior accessible, including appropriate button types and meaningful labels.
- Use state or event handlers for interactive values rather than modifying props.
17. Interview Questions and Answers
Q1. What is a reusable component in React?
Answer: A reusable component is a UI element that can be created once and used in multiple places in a React application.
Q2. Why do we use reusable components?
Answer: They reduce code duplication, improve consistency, simplify maintenance, and make applications easier to scale.
Q3. How can we customize a reusable component?
Answer: We can pass props to customize its content, appearance, and behavior.
Q4. What are props in React?
Answer: Props are read-only inputs that a parent component passes to a child component.
Q5. What is the children prop?
Answer: The children prop contains content nested between a component's opening and closing JSX tags.
Q6. Can one reusable component be rendered multiple times?
Answer: Yes. A component can be rendered multiple times with the same or different prop values.
Q7. Can reusable components receive functions as props?
Answer: Yes. A parent can pass a function, such as a click handler, through props so the component can trigger behavior.
Q8. Should props be modified inside a component?
Answer: No. Props should be treated as read-only. Use state for values that need to change over time.
Q9. Why should components be defined outside other components?
Answer: Defining components at the module's top level avoids creating a new component type on every parent render and helps prevent unexpected state resets.
Q10. What is the difference between a reusable component and a normal component?
Answer: Both are React components. The term reusable component emphasizes that the component is designed to work in multiple places or with different inputs.
Q11. Can reusable components contain other components?
Answer: Yes. React components can render other components, enabling developers to build complex interfaces from smaller pieces.
Q12. What are some examples of reusable components?
Answer: Buttons, cards, headers, navigation bars, form fields, product items, profile cards, alerts, and modal containers are common examples.
18. Practice Exercises
- Create a reusable Greeting component that accepts a name prop.
- Create a reusable Button component with label and variant props.
- Create a ProductCard component that accepts product name, category, and price.
- Create a ProfileCard component that displays a person's name and profession.
- Create a Card component that uses the children prop.
- Create a StudentCard component and use it to display five students from an array.
- Create a reusable StatusMessage component that displays success and error messages.
- Move a component into its own file and import it into App.jsx.
- Build a product catalogue using ProductCard, ProductList, and a page-level App component.
- Add CSS and ensure the reusable components remain visually consistent.
19. Quick Revision Checklist
- Understand the definition and purpose of reusable components.
- Know how to define and render a function component.
- Understand how to pass and read props.
- Know how to provide default prop values.
- Understand how to use the children prop.
- Know how to reuse components inside lists with stable keys.
- Understand how to export and import components between files.
- Recognize common mistakes when designing reusable components.
- Know when to extract a component and when a separate component is unnecessary.
- Practice building small applications with reusable UI elements.
20. Official React Documentation
21. React JS Training and Course Demo
Explore React JS training to learn component development, JSX, props, reusable UI patterns, and other frontend development concepts.
Conclusion
Reusable Components are an essential part of React development. They allow developers to create UI elements once and customize them through props and children. By organizing applications into focused, reusable components, developers can reduce duplication, maintain consistent design, and build applications that are easier to test, extend, and maintain.