React Components
React is a popular JavaScript library for building user interfaces, and at the heart of React lies the concept of components. Components are the building blocks of any React application, allowing developers to break down the UI into reusable, independent pieces. In this article, we will explore what React components are, their types, and how to use them effectively with examples.
What are React Components?
A React component is a reusable piece of code that defines how a part of the user interface should look and behave. Components can be thought of as JavaScript functions or classes that return React elements, which are then rendered to the DOM.
React components allow developers to:
- Break down complex UIs into smaller, manageable pieces.
- Reuse code across different parts of the application.
- Maintain a clear separation of concerns by encapsulating logic and UI.
Types of React Components
- Functional Components
- Class Components
Functional Components
- Functional components are simple JavaScript functions that accept props as an argument and return React elements.
- They are stateless by default but can manage state using React Hooks (e.g.,
useState,useEffect).
Example:
import React from 'react';
function Greeting (props) {
return <h1>Hello, {props.name}!</h1>;
}
export default Greeting;
Usage:
import React from 'react';
import ReactDOM from 'react-dom';
import Greeting from './Greeting';
ReactDOM.render(<Greeting name="John"/>, document.getElementById('root'));
Output:
Hello, John!
Class Components
- Class components are ES6 classes that extend
React.Component. - They can manage their own state and have access to lifecycle methods like
componentDidMount,componentDidUpdate, andcomponentWillUnmount.
Example:
import React, { Component } from'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state= { count:0 };
}
increment= () => {
this.setState({ count:this.state.count+1 });
};
render() {
return (
<div>
<h1>Count: {this.state.count}</h1>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
export default Counter;
Usage:
import React from 'react';
import ReactDOM from 'react-dom';
import Counter from './Counter';
ReactDOM.render(<Counter/>, document.getElementById('root'));
Output:
A counter with a button to increment the count.
