Skip to main content

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:

  1. 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>;
    }
  2. 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:

  1. Create a new JavaScript file (e.g., MyComponent.js).
  2. Import the React library.
  3. Define the component as a function.
  4. Return JSX from the function.
  5. 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:

  1. Create a new JavaScript file (e.g., MyClassComponent.js).
  2. Import the React library.
  3. Define the component as a class extending React.Component.
  4. Implement the render method.
  5. Return JSX from the render method.
  6. 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.