React is a powerful JavaScript library used to build fast and interactive user interfaces. Today, I learned about one of the core building blocks of React: Components and Props. Here's a summary of what I learned, with simple examples to help beginners understand easily.
What Are Components?
In React, components are like reusable blocks of code. They let us split the UI into independent, reusable pieces.
There are two main types of components:
- Functional Components (most common)
- Class Components (less used today, mostly in older codebases)
Functional Component Example
function Welcome() {
return <h1>Hello, React!</h1>;
}
export default Welcome;
You can use this component in your main app like this:
import Welcome from './Welcome';
function App() {
return (
<div>
<Welcome />
</div>
);
}
What Are Props?
Props (short for properties) are used to pass data from one component to another. Props make components dynamic and customizable.
Props Example
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
And in your App
component:
function App() {
return (
<div>
<Welcome name="Tamilselvan" />
<Welcome name="React Developer" />
</div>
);
}
This will render:
Hello, Tamilselvan!
Hello, React Developer!
Why Components and Props Matter
- Reusability: You can use components multiple times with different props.
- Separation of concerns: Keeps your code clean and organized.
- Dynamic UI: With props, components can adapt to different data.
Conclusion
Today, I learned how to create components and use props to pass data between them. These are the fundamentals of building any React app.
If you're also learning React, start by creating small components and practice passing props. It helps a lot!
Top comments (2)
Hey there! Great to see the steady progress, more power to you
Thank you for your kind words
Some comments may only be visible to logged-in visitors. Sign in to view all comments.