Components
What Are Components in React?
In React, components are the building blocks of a React application. A component is a self-contained module that renders some output. You can think of a component as a function that takes in parameters, called props
, and returns a React element that describes how a section of the UI should appear.
Components can be either Functional Components or Class Components:
Functional Components: These are simply JavaScript functions that return a React element. They are easier to write, understand, and test.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}Class Components: These are more traditional and use ES6 class syntax. They offer more features, like local state and lifecycle methods.
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
How to Create Components
Functional Component
Here's how you can create a functional component:
- Create a new JavaScript file (e.g.,
MyComponent.js
). - Import the React library.
- Define the component as a function.
- Return JSX from the function.
- Export the component.
// MyComponent.js
import React from 'react';
function MyComponent(props) {
return (
<div>
<h1>Hello, {props.name}!</h1>
</div>
);
}
export default MyComponent;
Class Component
Here's how you can create a class component:
- Create a new JavaScript file (e.g.,
MyClassComponent.js
). - Import the React library.
- Define the component as a class extending
React.Component
. - Implement the
render
method. - Return JSX from the
render
method. - Export the component.
// MyClassComponent.js
import React, { Component } from 'react';
class MyClassComponent extends Component {
render() {
return (
<div>
<h1>Hello, {this.props.name}!</h1>
</div>
);
}
}
export default MyClassComponent;
Using Components
Once you've defined a component, you can use it in other parts of your application like this:
import React from 'react';
import MyComponent from './MyComponent';
import MyClassComponent from './MyClassComponent';
function App() {
return (
<div>
<MyComponent name="John" />
<MyClassComponent name="Doe" />
</div>
);
}
export default App;
Here, MyComponent
and MyClassComponent
are being used in the App
component. The name
prop is passed to both components, which they use to render the output.