In React, a component is a piece of code that represents a part of a user interface. Components are reusable and can be thought of as building blocks for your app's user interface.
You can create a component in React by writing a JavaScript function or a class that returns a React element. Here's an example of a functional component that displays a simple message:
import React from 'react';
function MyComponent(props) {
return <div>Hello, {props.name}!</div>;
}
This component accepts a `props` object as an argument, which contains data that can be used to render the component. In this case, the component displays a `div` element containing a greeting to the user.
Functional Component
You can use this component in another component or in your app's main component by using the JSX syntax:
import React from 'react';
import MyComponent from './MyComponent';
function App() {
return (
<div>
<MyComponent name="John" />
<MyComponent name="Jane" />
</div>
);
}
This will render two instances of the `MyComponent` component, each with a different name passed as a prop.
Class Component
You can also create a class-based component by extending React.Component class:
import React, { Component } from 'react';
class MyComponent extends Component {
render() {
return <div>Hello, {this.props.name}!</div>;
}
}
Class-based components have additional features and capabilities, such as the ability to use state and lifecycle methods.
In both cases, the component is a pure function of its props, meaning that it will always render the same output for the same set of props. This makes it easy to reason about and test your components.
Comments (0)