In React, a component is a self-contained unit of code that encapsulates the structure (HTML), behavior (JavaScript), and styling (CSS) necessary to render a part of the user interface. Components can be thought of as the building blocks of a React application, each responsible for rendering a specific piece of the UI.
In ReactJS, we have mainly two types of components.
- Functional Components
- Class Components
1. Functional Components:
- These are JavaScript functions that return JSX (JavaScript XML), which describes what the UI should look like.
- They do not manage their own state; instead, they receive data through props (properties).
function Welcome(props) {
return Hello, {props.name}
;
}
2. Class Components:
- These are ES6 classes that extend React.Component and can manage their own state.
- They have lifecycle methods that allow them to execute code at specific points in the component’s life cycle.
class Welcome extends React.Component {
render() {
return Hello, {this.props.name}
;
}
}
Key Concepts
- JSX: A syntax extension that allows writing HTML-like code within JavaScript. JSX is then transpiled to JavaScript by tools like Babel.
const element = Hello, world!
;
- Props: Short for properties, props are read-only data passed from a parent component to a child component.
function Greeting(props) {
return Hello, {props.name}
;
}
- State: A built-in object that holds data that may change over the component’s lifecycle. State is managed within the component itself.
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
render() {
return It is {this.state.date.toLocaleTimeString()}.
;
}
}
Summary: A component in React is a reusable, independent piece of the UI that can be composed to build complex applications. They promote modularity and code reusability, making the development process more efficient and organized.