ReactJS is a popular JavaScript library used to build user interfaces. It is widely used due to its simplicity, efficiency, and high level of flexibility. One of the core concepts of ReactJS is components, which are modular and reusable building blocks that encapsulate a portion of a user interface.
In this blog, we will discuss the basics of ReactJS components, their types, and how to use them effectively.
What are ReactJS Components?
A ReactJS component is a JavaScript class or function that represents a part of the user interface. A component can be as small as a button or as large as an entire page. It encapsulates the presentation, behavior, and state of a portion of the UI.
ReactJS components are reusable and independent, which means they can be composed together to create complex UIs. Components can be nested within other components to form a hierarchical structure.
Types of ReactJS Components
There are two types of ReactJS components: functional components and class components.
Functional Components
Functional components are the simplest type of components in ReactJS. They are just plain JavaScript functions that accept props (short for properties) as input and return a React element.
Here is an example of a functional component:
function Button(props) {
return (
<button onClick={props.onClick}>
{props.label}
</button>
);
}
The Button component is a functional component that accepts two props: onClick and label. It returns a button element with the onClick handler and the label as its text.
Class Components
Class components are more powerful than functional components. They are JavaScript classes that extend the React.Component class and implement a render method. The render method returns a React element that describes the UI for the component.
Here is an example of a class component:
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
handleClick() {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={() => this.handleClick()}>Click me</button>
</div>
);
}
}
The Counter component is a class component that maintains a count in its state. It has a handleClick method that updates the count when the button is clicked. The render method returns a div element that displays the count and a button with the handleClick handler.
How to Use ReactJS Components
To use a ReactJS component, you need to import it into your code and render it in your application.
Here is an example of rendering a Button component:
import React from ‘react’;
import ReactDOM from ‘react-dom’;
import Button from ‘./Button’;
ReactDOM.render(
<Button label=”Click me” onClick={() => alert(‘Button clicked’)} />,
document.getElementById(‘root’)
);
The ReactDOM.render method renders the Button component with the label and onClick props into the root element in the HTML document.
Props
Props are inputs that a component receives from its parent component. They are read-only, which means that a component cannot modify its props. Instead, a component can use its props to determine what to render and how to behave.
Here’s an example of passing props to a component:
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
function App() {
return (
<div>
<Welcome name=”Alice” />
<Welcome name=”Bob” />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById(‘root’)
);
In this example, the Welcome component receives a name prop from its parent App component. The Welcome component uses the name prop to render a personalized greeting.
State
State is an internal data store of a component. It is mutable, which means that a component can modify its state. When a component’s state changes, React re-renders the component and its children.
Here’s an example of using state in a component:
class Clock extends React.Component {
constructor(props) {
super(props);
this.state = { date: new Date() };
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById(‘root’)
);
In this example, the Clock component uses its state to store the current date and time. The componentDidMount method sets up a timer to update the state every second. The componentWillUnmount method cleans up the timer when the component is unmounted.
Lifecycle Methods
React components have lifecycle methods that allow them to perform actions at certain points in their lifecycle, such as when they are mounted, updated, or unmounted.
Here are some commonly used lifecycle methods:
componentDidMount(): called after the component is mounted and rendered for the first time
componentDidUpdate(): called after the component is updated due to a change in its props or state
componentWillUnmount(): called before the component is unmounted and destroyed
Here’s an example of using a lifecycle method in a component:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
componentDidMount() {
console.log(‘Component mounted’);
}
componentDidUpdate(prevProps, prevState) {
console.log(‘Component updated’, prevProps, prevState);
}
componentWillUnmount() {
console.log(‘Component unmounted’);
}
render() {
return <div>Count: {this.state.count}</div>;
}
}
ReactDOM.render(
<Example />,
document.getElementById(‘root’)
);
Conclusion
ReactJS components are a fundamental concept in building scalable and maintainable user interfaces. They allow you to break down complex UIs into small, reusable building blocks. Components can receive inputs through props and maintain internal state. They also have lifecycle methods that allow them to perform actions
At LearnTube, we provide a wide range of online courses designed to enhance your ReactJS skills. LearnTube is equipped with powerful learning tools such as a dedicated app and WhatsApp bot, ensuring an excellent learning experience. Regardless of whether you are a beginner or an advanced learner, we offer a vast selection of courses that cater to your needs. Visit our website today and browse through our comprehensive course offerings to take your ReactJS skills to the next level.