Creating Components in React
Key Concepts
- Functional Components: Components defined as JavaScript functions that return JSX.
- Class Components: Components defined as ES6 classes that extend React.Component.
- Props: Inputs passed to components to make them dynamic and reusable.
Functional Components
Functional components are simple JavaScript functions that return JSX. They are easier to write and understand, making them ideal for small to medium-sized components.
Example:
function Welcome(props) { return <h1>Hello, {props.name}</h1>; }
In this example, Welcome
is a functional component that takes props
as an argument and returns an h1
element with a greeting message.
Class Components
Class components are defined using ES6 classes and extend the React.Component
class. They are more powerful and can include state and lifecycle methods.
Example:
class Welcome extends React.Component { render() { return <h1>Hello, {this.props.name}</h1>; } }
Here, Welcome
is a class component that renders an h1
element with a greeting message using the name
prop.
Props
Props (short for properties) are inputs to a component that make it dynamic and reusable. They are passed from parent components to child components and can be accessed within the component.
Example:
function App() { return ( <div> <Welcome name="Alice" /> <Welcome name="Bob" /> </div> ); }
In this example, the App
component renders two Welcome
components, each with a different name
prop.
Analogies
Think of a functional component as a simple recipe that takes ingredients (props) and produces a dish (JSX). A class component, on the other hand, is like a chef who not only prepares the dish but also manages the kitchen (state and lifecycle methods).
Props are like instructions passed from a parent to a child. For example, a parent might tell a child to draw a picture of a cat. The child follows the instructions and draws the picture, but the parent doesn't need to know how the drawing is done.