React Components
React components are the building blocks of any React application. They are reusable pieces of code that define the structure and behavior of a part of the user interface.
In React, components can be created using either class components or function components.
Class Components
Class components are created by extending the React.Component
class. They have a render()
method that returns the component's HTML representation. Class components are useful when the component needs to have its own state or lifecycle methods.
Here's an example of a class component:
1import React from 'react';
2
3class Button extends React.Component {
4 render() {
5 return (
6 <button>{this.props.label}</button>
7 );
8 }
9}
Function Components
Function components are created by writing a JavaScript function that returns the component's HTML representation. Function components are simpler and easier to write compared to class components. They are useful when the component doesn't need to manage its own state or lifecycle methods.
Here's an example of a function component:
1import React from 'react';
2
3function Button(props) {
4 return (
5 <button>{props.label}</button>
6 );
7}
To use a component, you can simply import it and include it in the JSX code of another component. Here's an example of how to use the Button
component:
1import React from 'react';
2import Button from './Button';
3
4function App() {
5 return (
6 <div>
7 <h1>Example App</h1>
8 <Button label="Click Me" />
9 </div>
10 );
11}
In this example, the App
component includes the Button
component, which will render a button with the label "Click Me".
xxxxxxxxxx
// Component example
import React from 'react';
class Button extends React.Component {
render() {
return (
<button>{this.props.label}</button>
);
}
}
// Using the component
import React from 'react';
import Button from './Button';
function App() {
return (
<div>
<h1>Example App</h1>
<Button label="Click Me" />
</div>
);
}
export default App;