Understanding React Components
Components are the building blocks of any React application. They allow you to break down your UI into independent, reusable pieces. Think of them as custom HTML elements that can have their own logic and appearance.
Functional Components
Functional components are the most common type of component in modern React. They are JavaScript functions that accept props as an argument and return React elements.
function WelcomeMessage(props) {
return Hello, {props.name}!
;
}
// Usage:
// <WelcomeMessage name="World" />
Class Components
Class components were the primary way to create components before the introduction of hooks. They are ES6 classes that extend React.Component
and have a render
method that returns React elements. While still supported, functional components with hooks are generally preferred.
class Greeting extends React.Component {
render() {
return <h2>Welcome, {this.props.userName}!</h2>;
}
}
// Usage:
// <Greeting userName="Alice" />
JSX (JavaScript XML)
JSX is a syntax extension for JavaScript that looks similar to HTML. It allows you to write your UI structure directly within your JavaScript code. React uses JSX to define how the UI should look. When you write JSX, it gets compiled into regular JavaScript function calls.
For example, this JSX:
const element = <h1>Hello, JSX!</h1>;
Gets compiled into something like this JavaScript:
const element = React.createElement('h1', null, 'Hello, JSX!');
Props (Properties)
Props are how you pass data from a parent component to a child component. They are read-only and are passed down the component tree. Think of them as function arguments.
function UserProfile(props) {
return (
<div>
<h3>{props.user.name}</h3>
<p>Email: {props.user.email}</p>
</div>
);
}
// Usage:
// const userData = { name: 'Bob', email: 'bob@example.com' };
// <UserProfile user={userData} />
Interactive Example: A Simple Counter Component
Let's see a functional component in action that manages its own state (though we'll cover state more deeply later). For now, observe how it re-renders when the button is clicked.
Interactive Counter
Current Count: 0
Note: The interactive example above uses JavaScript to simulate React's state management for demonstration purposes. In a real React application, you would use the useState
hook.
Next Steps
Now that you have a basic understanding of React components, you're ready to dive deeper into how components manage their internal data using State and how to pass data between them using Props.