In React, a component is a piece of code that represents a part of a user interface. Components can be reused throughout an application, which makes it easier to build and maintain large applications.
There are two types of components in React: functional components and class-based components.
Functional components are simple functions that take in props (short for properties) and return a React element. Here’s an example of a functional component:
import React from 'react';
function MyComponent(props) {
return <h1>Hello, {props.name}!</h1>;
}
export default MyComponent;
This component takes in a prop called ‘name‘ and renders an ‘h1‘ element with the text “Hello, [name]!”.
Class-based components are created using JavaScript classes. They can have state (data that can change over time) and lifecycle methods (methods that are called at specific points in a component’s lifecycle). Here’s an example of a class-based component:
import React from 'react';
class MyComponent extends React.Component {
state = {
name: 'John',
};
render() {
return <h1>Hello, {this.state.name}!</h1>;
}
}
export default MyComponent;
This component has a state variable called ‘name‘ and a ‘render()‘ method that returns an ‘h1‘ element with the text “Hello, [name]!”.
You can use either type of component in a React app, depending on your needs. Functional components are simpler and easier to write, but class-based components are more powerful and can have state and lifecycle methods.