Creating React Components
Creating React Components is an essential concept in React JS. Components allow developers to divide a user interface (UI) into small, reusable, and independent parts. Instead of writing an entire website in one large file, developers can create separate components for the header, navigation bar, sidebar, product cards, forms, and footer.
Course: React JS Training
Course Link: JustAcademy React JS Training Course
Demo Link: Register for React JS Course Demo
1. What Are React Components?
A React component is a reusable building block of a user interface. It can represent a small element, such as a button, or a larger section, such as a complete page. Components help organize code and make applications easier to develop, test, and maintain.
For example, an e-commerce website may contain the following components:
- Header: Displays the website logo and main navigation.
- Navbar: Displays links to different sections.
- ProductCard: Displays product information and price.
- SearchBar: Allows users to search for products.
- ShoppingCart: Displays selected products.
- Footer: Displays contact details and other links.
Each component can be created separately and combined to build the complete application.
2. Types of React Components
React supports function components and class components. Function components are generally preferred when creating new components in modern React applications.
2.1 Functional Components
A functional component is a JavaScript function that returns React elements, usually using JSX.
function Welcome() {
return <h1>Welcome to React JS!</h1>;
}
export default Welcome;
Here, Welcome is a functional component that displays a heading.
2.2 Class Components
A class component is defined using a JavaScript class that extends React.Component. It typically uses a render() method to return JSX.
import { Component } from "react";
class Welcome extends Component {
render() {
return <h1>Welcome to React JS!</h1>;
}
}
export default Welcome;
Class components are still supported, but function components are generally recommended for new React code.
3. Basic Syntax for Creating a React Component
The following example demonstrates the basic structure of a function component.
function ComponentName() {
return (
<div>
<h1>Hello World</h1>
<p>This is my first React component.</p>
</div>
);
}
export default ComponentName;
Explanation:
function ComponentName() defines the component function.
return specifies the UI to render.
div, h1, and p are JSX elements.
export default makes the component available for importing into another module.
4. Rules for Creating React Components
- Use a capital letter: Custom React component names should start with an uppercase letter, such as
Header or ProductCard.
- Return valid React content: A component should return a valid React-renderable value, commonly JSX.
- Use valid JSX syntax: Close tags properly and use a parent element or Fragment when returning multiple adjacent elements.
- Keep components reusable: Use props to customize the same component with different data.
- Keep component definitions at the top level: Avoid defining one component function inside another component function.
- Keep rendering pure: A component should calculate its UI from its inputs and state rather than performing side effects during rendering.
5. Creating Your First React Component
Step 1: Create a React Project
You can create a React project using Vite.
npm create vite@latest my-react-app -- --template react
cd my-react-app
npm install
npm run dev
These commands create a React project, install its dependencies, and start the development server.
Step 2: Create a Component File
Inside the src folder, create a file named Welcome.jsx.
function Welcome() {
return (
<div>
<h1>Welcome to My Website</h1>
<p>This is my first custom component.</p>
</div>
);
}
export default Welcome;
Step 3: Import the Component
Open App.jsx and import the newly created component.
import Welcome from "./Welcome";
function App() {
return (
<div>
<Welcome />
</div>
);
}
export default App;
Step 4: View the Output
When you run the React application, the browser displays the heading “Welcome to My Website” and the paragraph beneath it. The App component renders the Welcome component.
6. Using Arrow Functions to Create Components
Function components can also be written using arrow-function syntax.
const Greeting = () => {
return (
<div>
<h2>Hello, React Developer!</h2>
<p>You have created an arrow-function component.</p>
</div>
);
};
export default Greeting;
For simple components, you can use an implicit return.
const Greeting = () => <h2>Hello, React Developer!</h2>;
export default Greeting;
Both approaches are valid. Select the syntax that makes your code clear and readable.
7. Creating Multiple Components
A React application can contain multiple components, each responsible for a specific part of the interface.
function Header() {
return <h1>My Website</h1>;
}
function MainContent() {
return <p>Welcome to our website.</p>;
}
function Footer() {
return <footer>Copyright 2026</footer>;
}
function App() {
return (
<div>
<Header />
<MainContent />
<Footer />
</div>
);
}
export default App;
In this example, the application uses three separate components. The App component combines them into one interface.
8. Creating Components in Separate Files
In larger applications, it is good practice to organize related components into separate files. This makes the code easier to understand and maintain.
Example Project Structure:
src/
components/
Header.jsx
Navbar.jsx
Footer.jsx
ProductCard.jsx
App.jsx
main.jsx
Header.jsx
function Header() {
return <header><h1>Online Store</h1></header>;
}
export default Header;
Navbar.jsx
function Navbar() {
return (
<nav>
<a href="/">Home</a>
{" "}
<a href="/products">Products</a>
{" "}
<a href="/contact">Contact</a>
</nav>
);
}
export default Navbar;
Footer.jsx
function Footer() {
return <footer>Thank you for visiting our store.</footer>;
}
export default Footer;
App.jsx
import Header from "./components/Header";
import Navbar from "./components/Navbar";
import Footer from "./components/Footer";
function App() {
return (
<div>
<Header />
<Navbar />
<main>
<h2>Welcome to our Online Store</h2>
</main>
<Footer />
</div>
);
}
export default App;
Each component is exported from its own file and imported into App.jsx. This structure becomes especially useful as the application grows.
9. Importing and Exporting Components
Exporting allows a component to be used in other files. Importing makes the exported component available where it is needed.
Default Export:
function Profile() {
return <h2>User Profile</h2>;
}
export default Profile;
Import a default export without curly braces:
import Profile from "./Profile";
Named Export:
export function Header() {
return <h1>Website Header</h1>;
}
export function Footer() {
return <footer>Website Footer</footer>;
}
Import named exports using curly braces:
import { Header, Footer } from "./Layout";
A file can have multiple named exports but only one default export. Choose an export style and use its matching import syntax.
10. Nesting Components
Nesting means rendering one component inside another. It helps organize the interface into a hierarchy.
function Button() {
return <button>Click Me</button>;
}
function Card() {
return (
<div>
<h2>Welcome Card</h2>
<p>This card contains a reusable button.</p>
<Button />
</div>
);
}
function App() {
return <Card />;
}
export default App;
Here, Card renders Button, and App renders Card. Define components at the top level of the module instead of declaring them inside another component.
11. Passing Data to Components Using Props
Props allow a parent component to send data to a child component. They make components reusable with different content.
function StudentCard({ name, course }) {
return (
<div>
<h2>{name}</h2>
<p>Course: {course}</p>
</div>
);
}
function App() {
return (
<div>
<StudentCard name="Amit" course="React JS" />
<StudentCard name="Priya" course="JavaScript" />
</div>
);
}
export default App;
The same StudentCard component displays different names and courses because each instance receives different props. Treat props as read-only values.
12. Passing Children to Components
The special children prop lets a component display content placed between its opening and closing tags.
function Card({ children }) {
return (
<div className="card">
{children}
</div>
);
}
function App() {
return (
<Card>
<h2>React JS</h2>
<p>Learn to build reusable components.</p>
</Card>
);
}
export default App;
The content placed inside <Card>...</Card> is passed to the component through children. This pattern is useful for cards, layouts, dialogs, and reusable containers.
13. Creating Components with Dynamic Data
Components can display JavaScript values using curly braces in JSX. This allows the UI to change according to the data passed into the component.
function Product({ name, price }) {
return (
<div>
<h3>{name}</h3>
<p>Price: ₹{price}</p>
</div>
);
}
function App() {
return (
<div>
<Product name="Keyboard" price={999} />
<Product name="Mouse" price={499} />
</div>
);
}
export default App;
String props can be written in quotes, while JavaScript values such as numbers and expressions are passed inside curly braces.
14. Conditional Rendering in Components
Conditional rendering means showing different content based on a condition.
function LoginMessage({ isLoggedIn }) {
if (isLoggedIn) {
return <h2>Welcome Back!</h2>;
}
return <h2>Please Log In</h2>;
}
function App() {
return (
<div>
<LoginMessage isLoggedIn={true} />
<LoginMessage isLoggedIn={false} />
</div>
);
}
export default App;
The first instance displays a welcome message, while the second asks the user to log in.
15. Rendering Lists of Components
The map() method can create multiple component instances from an array of data. Use a stable, unique key for each item among its siblings.
function ProductList() {
const products = [
{ id: 1, name: "Laptop" },
{ id: 2, name: "Keyboard" },
{ id: 3, name: "Mouse" }
];
return (
<ul>
{products.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
);
}
export default ProductList;
React uses the keys to identify list items between renders. Stable identifiers from the data are preferable to array indexes when the list can change.
16. Styling React Components
Components can be styled using CSS classes. In JSX, use className instead of the HTML attribute class.
ProductCard.jsx
function ProductCard() {
return (
<div className="product-card">
<h2>Wireless Headphones</h2>
<p>Comfortable headphones for everyday use.</p>
<button>Buy Now</button>
</div>
);
}
export default ProductCard;
App.css
.product-card {
border: 1px solid #cccccc;
padding: 16px;
border-radius: 8px;
max-width: 300px;
}
.product-card button {
padding: 8px 12px;
cursor: pointer;
}
Import the stylesheet into the appropriate application or component entry file, for example with import "./App.css";.
17. Components and State
When a component needs to track changing information, it can use the useState Hook.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default Counter;
The state setter requests an update, and React renders the component again with the new state. Hooks must be called at the top level of a function component or custom Hook, not inside loops or conditions.
18. React Components vs HTML Elements
| Feature |
HTML Element |
React Component |
| Example |
<button> |
<SubmitButton /> |
| Naming |
Built-in HTML tags are lowercase |
Custom component names begin with a capital letter |
| Purpose |
Provides built-in browser UI structure |
Encapsulates reusable UI and related logic |
| Reuse |
HTML tags can be repeated |
Components can be reused and customized with props |
| Composition |
Elements can contain other elements |
Components can render elements and other components |
19. Advantages of Creating React Components
- Reusability: Write a component once and use it in multiple places.
- Maintainability: Small components make code easier to update and debug.
- Organization: Divide a large application into logical sections.
- Consistency: Reuse the same UI structure across pages.
- Testability: Test individual components separately.
- Scalability: Add new features without placing all code in one large component.
- Team collaboration: Developers can work on different components independently.
20. Common Mistakes When Creating Components
| Mistake |
Problem |
Correct Approach |
| Using lowercase component names |
React treats lowercase JSX tags as HTML-like elements. |
Use names such as Header and Profile. |
| Forgetting to export a component |
Other modules cannot import it using the expected export. |
Use a default or named export as appropriate. |
| Using incorrect import syntax |
The import does not match the type of export. |
Use braces for named exports and no braces for default exports. |
| Returning adjacent JSX elements |
JSX requires adjacent elements to share a parent. |
Use a parent element or React Fragment. |
| Defining components inside components |
New component types may be created on each render, causing performance and state issues. |
Define component functions at module scope. |
| Modifying props directly |
Props are read-only inputs. |
Pass updated data from the parent or manage appropriate local state. |
| Missing list keys |
React cannot reliably track list items between renders. |
Provide stable keys such as database IDs. |
21. Practical Project: Simple Course Website
Create a small course website by combining multiple reusable components.
Requirements:
- Create a
Header component for the website title.
- Create a
Navbar component for navigation links.
- Create a
CourseCard component that accepts a course name, description, and price.
- Create a
CourseList component that renders multiple course cards.
- Create a
Footer component for contact information.
- Import all the components into
App.jsx.
- Add CSS to make the course cards visually clear.
- Run the project and verify that all components display correctly.
Example CourseCard Component:
function CourseCard({ title, description, price }) {
return (
<div className="course-card">
<h2>{title}</h2>
<p>{description}</p>
<p>Price: ₹{price}</p>
<button>View Course</button>
</div>
);
}
export default CourseCard;
22. Interview Questions and Answers
Q1. What is a React component?
Answer: A React component is a reusable unit of UI that can include markup and logic. It is commonly defined as a JavaScript function returning JSX.
Q2. What are the main types of React components?
Answer: Function components and class components. Function components are generally recommended for new React code.
Q3. Why do component names start with capital letters?
Answer: Capitalization tells JSX to treat a tag as a custom React component rather than a built-in HTML element.
Q4. What is the purpose of export and import?
Answer: Export makes a component available outside its module, and import allows another module to use it.
Q5. What are props?
Answer: Props are inputs passed from a parent component to a child component to customize its output.
Q6. Can a component contain another component?
Answer: Yes. A component can render another component inside its JSX. This is called component composition or nesting.
Q7. What is the difference between default and named exports?
Answer: A module can have one default export and multiple named exports. Default imports do not use braces, while named imports do.
Q8. Why should components be reusable?
Answer: Reusable components reduce duplicated code, improve consistency, and make applications easier to maintain.
Q9. What is the purpose of the children prop?
Answer: The children prop contains content nested between a component's opening and closing tags.
Q10. How can a component display changing data?
Answer: It can receive updated props from its parent or manage local state with Hooks such as useState.
23. Quick Revision Checklist
- Understand what React components are and why they are used.
- Create function components using JavaScript functions or arrow functions.
- Use capitalized names for custom components.
- Understand JSX syntax and React Fragments.
- Import and export components correctly.
- Organize components into separate files.
- Compose parent and child components.
- Pass data through props and children.
- Render conditional content and lists with stable keys.
- Use CSS to style components.
- Manage changing data with state when needed.
- Follow React component and Hook best practices.
24. Conclusion
Creating React Components is a fundamental skill for building modern React applications. Components divide a user interface into smaller, reusable units that can be imported, combined, styled, and customized with props. Understanding component creation, file organization, JSX, and component composition helps developers build applications that are easier to maintain and extend.
Learn more through the JustAcademy React JS Training Course.
To explore a course demonstration, visit Register for React JS Course Demo.