What Are Components and Props?

In React, components and props are the core concepts that let you build an application from independent, reusable pieces. Here is a closer look at both:
Components
Definition: Components are the independent, reusable pieces that make up the user interface in React. A React application usually consists of many components.
Types:
- Function components: Defined as JavaScript functions; they receive inputs called props and return the React elements to display. Example: function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
- Class components: Defined as JavaScript classes; their render method returns the React elements to display. Example: class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
Reuse and composition: Components make code reusable; small components can be combined into bigger ones.
Props
Definition: Props pass data into components. A component can read the props it receives but must not change them (they are read-only).
Usage: Passing a prop looks like adding an attribute to an HTML element. Example: in <Welcome name="Sara" />, name is a prop.
Communication between components: Data flows from parent to child components through props.
Reading props: Function components receive props as the function's parameter; class components read them from this.props.
Example
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahit" />
<Welcome name="Eda" />
</div>
);
}Here the Welcome component is used three times, each time with a different name prop. The App component combines them into a single UI.
Components and props let you build React applications in a modular way, so even complex user interfaces stay manageable and easy to understand.
Have a question about this article? Write to me


