How to create components in React?

There are two main ways to create components in React: function components and class-based components.

Function components are simple functions that accept props (short for “properties”) as an argument and return a JSX element. Here is an example of a function component that displays a greeting:

import React from 'react';

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

Function components are a concise and easy way to create simple components that do not have their own state or lifecycle methods. They are often referred to as “stateless” components.

Class-based components are defined using JavaScript classes that extend the React.Component class and define a render() method, which returns a JSX element. Here is an example of a class-based component that displays a greeting:

import React from 'react';

class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

Class-based components are more powerful and flexible than function components, as they can have their own state, lifecycle methods, and other features. They are often referred to as “stateful” components.

To use a component in your application, you can import it and render it using JSX syntax:

import React from 'react';
import ReactDOM from 'react-dom';
import Greeting from './Greeting';

ReactDOM.render(
  <Greeting name="John" />,
  document.getElementById('root')
);

This will render the `Greet`

Leave a Comment