In the React JavaScript library for building user interfaces, a `component` is a reusable piece of code that represents a part of a user interface. Components can be thought of as the building blocks of a React application, and they can be either functional or class-based.
Here are some of the main components of a React application:
- `Props` (short for "properties") are input values that are passed to a component when it is rendered. They are used to customize the behavior and appearance of a component.
- `State` is an object that represents the internal, mutable state of a component. It is used to store data that can change within a component and trigger a re-render when it does.
- `Render` method is a required method in a class-based component that returns a description of what the component should render. In a functional component, the `render` method is implicit and the component returns the description directly.
- `Lifecycle methods` are optional methods that can be defined in a class-based component to execute code at specific points in the component's lifecycle. Examples include `componentDidMount`, which is called after the component has been rendered to the DOM, and `shouldComponentUpdate`, which is called before a re-render and can be used to optimize performance by canceling the update if certain conditions are met.
Here is an example of a functional component in React:
import React from 'react';
const MyComponent = (props) => {
return (
<div>
<h1>{props.title}</h1>
<p>{props.description}</p>
</div>
);
}
export default MyComponent;
And here is an example of a class-based component in React:
import React, { Component } from 'react';
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<h1>{this.props.title}</h1>
<p>{this.props.description}</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
<p>You've clicked the button {this.state.count} times.</p>
</div>
);
}
}
export default MyComponent;
Comments (0)