Embedding components in React is a way of organizing and breaking down your UI (User Interface) into smaller, reusable pieces. In React, you can create components to represent parts of your user interface and then embed them within each other to build a complete UI.
Why Embed Components?
React encourages breaking your UI into small, reusable pieces (components). Following are the benefits of component embedding.
1. Reusability: Components can be reused across different parts of your application, which reduces code duplication.
2. Separation of Concerns: Each component can focus on a single part of the UI, making it easier to manage and maintain.
3. Better Organization: Embedding components helps you structure your code in a modular way, which is easier to read and maintain.
Example
Assume I want to build a simple UI to display Employee Profile like name, email, and address. We can break it down into multiple components.
1. EmployeeBasicDetails
2. Address
3. Hobbies
4. Experience
Refer the file ‘EmployeeProfile.jsx’ to get an example.
Following step-by-step procedure helps you to build the complete working application.
Step 1: Go to the post (Quickly Set Up aReact Project with Vite: A Step-by-Step), and set up a React Project ‘components-embedding’
Project structure looks like below.
Step 2: Create components folder in src/ folder and EmployeeProfile component in it.
EmployeeProfile.jsx
function EmployeeBasicDetails() {
return (
<div>
<h2>Employee Name: Rama Krishan</h2>
<h3>Position: Software Engineer</h3>
<h3>Email: krishna@example.com</h3>
</div>
);
}
function Address() {
return (
<div>
<h3>Address:</h3>
<p>Chowdeswari Street, Bangalore</p>
</div>
);
}
function Hobbies() {
return (
<div>
<h3>Hobbies:</h3>
<ul>
<li>Reading</li>
<li>Cycling</li>
<li>Cooking</li>
</ul>
</div>
);
}
function Experience() {
return (
<div>
<h3>Experience:</h3>
<ul>
<li>Company A: 2018 - Present (Software Engineer)</li>
<li>Company B: 2015 - 2018 (Junior Developer)</li>
</ul>
</div>
);
}
export default function EmployeeProfile() {
return (
<div>
<EmployeeBasicDetails />
<Address />
<Hobbies />
<Experience />
</div>
);
}
Step 4: Update main.jsx file like below.
main.jsx
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import EmployeeProfile from './components/EmployeeProfile'
createRoot(document.getElementById('root')).render(
<StrictMode>
<EmployeeProfile />
</StrictMode>,
)
Step 5: Build and run the application.
cd components-embedding npm install npm run dev
Open the url ‘http://localhost:5173/’ in browser, you can see below screen.
You can download this application from this link.
No comments:
Post a Comment