React Components (Functional & Class)

  • Share this:

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, {}!</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 (
      <MyComponent name="John" />
      <MyComponent name="Jane" />

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, {}!</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.


About author
I am a professional web developer. I love programming and coding, and reading books. I am the founder and CEO of StorialTech.