06_Components - Maniconserve/React-Wiki GitHub Wiki
A component is a reusable piece of UI. It takes some input (called props) and returns JSX to display on screen.
React has two ways to write components.
Same Example — Two Ways
Both examples below do exactly the same thing: display a greeting card with a name and message.
1. Functional Component
A plain JavaScript function that returns JSX.
function GreetingCard(props) {
return (
Hello, {props.name}!
{props.message}
);
}
// Usage
2. Class Component
A JavaScript class that extends React.Component and uses a render() method to return JSX.
import React from 'react';
class GreetingCard extends React.Component {
render() {
return (
Hello, {this.props.name}!
{this.props.message}
);
}
}
// Usage
Notice: In a class component you must write
this.propsto access props. In a functional component, props come in directly as a function argument.
Key Differences
| Functional | Class | |
|---|---|---|
| Syntax | Plain function | class extending React.Component |
| Accessing props | props.name |
this.props.name |
render() method |
❌ Not needed | ✅ Required |
| State & Lifecycle | Via Hooks (useState, useEffect) |
Built-in (this.state, componentDidMount) |
| Code length | Shorter | More boilerplate |
| Modern standard | ✅ Yes | ❌ Older style |
Which Should You Use?
Always use Functional Components. They are the modern standard in React.
Class components are older and mainly seen in legacy codebases. React introduced Hooks (like useState and useEffect) in version 16.8, which gave functional components everything class components could do — but with less code and simpler syntax.
props — Passing Data Into a Component
Props let you pass data from a parent component into a child component, similar to passing arguments into a function.
// Parent
function App() {
return ;
}
// Child (Functional)
function GreetingCard(props) {
return Hello, {props.name}!;
}
Props are read-only. A component should never modify its own props.