React Tutorials - Quotes App -104- DRY Principle
What is DRY?
DRY (Don’t Repeat Yourself) is a fundamental principle of software development that aims to reduce code duplication by extracting repeated code into reusable components.
Implementing DRY in our Quotes App
We noticed that both the Home Page and Quotes Page use identical code to render quotes. Let’s refactor this duplicate code into a reusable Quote component.
Creating the Quote Component
- Create a new file
Quote.jsxin thecomponentsfolder - Add the following code:
interface QuoteType {
_id: string;
quote: string;
author: string;
}
interface QuoteProps {
quote: QuoteType;
}
function Quote({ quote }: QuoteProps) {
return (
<div className="card mt-3">
<div className="card-body">
<blockquote className="blockquote mb-0">
<p>{quote.quote}</p>
<footer className="blockquote-footer mt-2">{quote.author}</footer>
</blockquote>
</div>
</div>
)
}
export default Quote
- Update
QuotePage.jsxto use the new component:
{quotes.map((quote) => (
<Quote quote={quote} key={quote._id} />
))}
- Update
HomePage.jsxto use the same component:
<Quote quote={quoteOfDay} />
Adding Author Links
Configure Route Parameters
- Update
App.tsxto handle author-specific routes:
<Route path="/quotes" element={<QuotePage />} />
<Route path="/quotes/:author" element={<QuotePage />} />
- Modify
AuthorPage.tsxto create author links:
<Link to={`/quotes?author=${encodeURIComponent(author)}`}>
- Update
QuotePage.tsxto handle author-specific quotes:
import { useSearchParams } from 'react-router-dom';
export default function QuotePage() {
const [searchParams] = useSearchParams();
const author = searchParams.get('author');
// Filter quotes if author parameter exists
const displayedQuotes = author
? quotes.filter(q => q.author === decodeURIComponent(author))
: quotes;
return (
// ... existing JSX using displayedQuotes
);
}
Project Structure After Changes
src/
├── components/
│ └── Quote.tsx # New reusable quote component
├── pages/
│ ├── HomePage.tsx # Updated to use Quote component
│ ├── QuotePage.tsx # Updated to use Quote component
│ └── AuthorPage.tsx # Updated with author links
└── App.tsx # Updated with new routes
| « Previous | Index | Next » |