How to Create a React Component: A Step-by-Step Guide

React components are the building blocks of any React application. They let you split the UI into independent, reusable pieces. In this tutorial, you’ll learn how to create both functional and class components, the two main types.

A React component is essentially a JavaScript function (or class) that returns JSX — a syntax extension that looks like HTML. The simplest way to create one is using a function.

Article illustration

Creating a Functional Component

Functional components are the modern standard. Write a JavaScript function that returns JSX:

  • Define a function with a capital letter (e.g., Greeting).
  • Return a single root element inside JSX.
  • Export the component to use it elsewhere.

Example: function Greeting() { return <h1>Hello, World!</h1>; }

Adding Props

Pass data to components via props. Accept props as an argument:

  • Use props.name inside JSX.
  • Set default values with destructuring: function Greeting({ name = "User" }).

Creating a Class Component

Before hooks, class components were common. They extend React.Component and must have a render() method:

  • Import React.
  • Define class: class Greeting extends React.Component.
  • Inside render(), return JSX.
  • Access props via this.props.

Managing State (Class Only)

Class components can hold state using this.state and update with this.setState().

Using State in Functional Components (Hooks)

Modern React uses the useState hook for state inside functions:

  • Import useState from React.
  • Call: const [count, setCount] = useState(0);
  • Update with setCount(newValue).

Creating React components is straightforward. Start with functional components and hooks for simplicity. Remember to name components with capital letters and always export them. Build your UI by composing these small, reusable pieces.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *