React Components
By Saket Bhatnagar••Beginner to Intermediate
components
- 1React components are the building blocks of a React application
- 2They let you split the UI into smaller, reusable parts instead of writing everything in one file
- 3A component is like a function that returns HTML using JSX (JavaScript + HTML)
- 4For example, you can create a Header component for your website’s top section with logo and links
- 5
Example: Create a Header component
1const Header = () => {2 return <div>Header</div>;3 } - 6You can also create a Footer component for the bottom section and a MainContent component for the center
- 7
Example: Create a Footer component
1const Footer = () => {2 return <div>Footer</div>;3 } - 8
Example: Create a MainContent component
1const MainContent = () => {2 return <div>MainContent</div>;3 } - 9Each component is like a mini webpage section you design once and reuse wherever needed
- 10Instead of repeating the same HTML code, you write a component and use it like a custom tag <Header />, <MainContent />, <Footer />
- 11Component names must be in PascalCase (capital letters for each word) Header, MainContent, Footer
- 12In React, you can use <Header />, <MainContent />, <Footer /> to display all sections together like this:
Example: Use components
1<body>2 <Header />3 <MainContent />4 <Footer />5</body> - 13This keeps your code clean, organized, and easy to manage
- 14React components can also accept inputs (called props) like js functions arguments and manage their own data (called state) like js functions variables.
- 15With components, you focus on building small parts of UI and then combine them to build full web pages
- 16We have two types of components:
- Function components are simpler and more straightforward for most use cases.
- Class components are more complex and less straightforward for most use cases.
Create components using function or class components.Example: Create a component using function
1const Header = () => {2 return <div>Header</div>;3 }Example: Create a component using class
1class Header extends React.Component {2 render() {3 return <div>Header</div>;4 }5 }
Which one to use?
Use function components are more popular and easier to use for most use cases.