React Component

A React component describes a part of the UI. Its purpose is to return HTML to a web page.

There are two ways to create React components.

Function Component

import React from "react";

function App(props){
  return <h1>Hello World</h1>
} 

export default App;
  • The name must have an uppercase first letter.
  • The function component must be the default export.
  • The function must return a React element (can use JSX).
  • The argument props can be omitted if "props" are not used.
  • There is no need to import React from 'react' (since React 17).
  • Function components used to be called "state-less components."
  • With the introduction of "Hooks" (since React 18), function components can hold "state."

You can define function components using the arrow function.

const App = () => {
  return <h1>Hello World</h1>
} 

export default App;

Class Component

import React, { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    this.state = { 
      greeting: "Hello World" 
    }
  }

  render() {
    return (
      <h1>{this.state.greeting}</h1>
    );
  }
} 

export default App;
  • A class component must extend the Component class from react library.
  • A class component must have a render method that a React element (can use JSX).
  • A class component should have a constructor that receives a props argument and passes it to the parent constructor (using the super keyword). If the constructor has no other purpose, it can be omitted.
  • The class component must be the default export.
  • Class components are also called state-full components.
  • The component's "state" must be stored in an object called state. This object must be a class property. It can be declared inside the constructor or as a field.
import React, { Component } from "react";

class App extends Component {
  state = { 
    greeting: "Hello World" 
  }

  render() {
    return (
      <h1>{this.state.greeting}</h1>
    );
  }
} 

export default App;