0
0
ReactHow-ToBeginner · 3 min read

How to Create a Component in React: Simple Guide

In React, you create a component by writing a function that returns JSX, which looks like HTML but works in JavaScript. Use a function with a name starting with a capital letter and return the UI inside it to define a component.
📐

Syntax

A React component is a JavaScript function that returns JSX. JSX is a syntax that looks like HTML but is used inside JavaScript to describe the UI.

The function name must start with a capital letter to be recognized as a component. The function returns JSX wrapped in parentheses.

jsx
function ComponentName() {
  return (
    <div>
      {/* UI elements go here */}
    </div>
  );
}
💻

Example

This example shows a simple React component named Greeting that displays a welcome message. It returns a <div> with text inside.

jsx
import React from 'react';

function Greeting() {
  return (
    <div>
      <h1>Hello, welcome to React!</h1>
    </div>
  );
}

export default Greeting;
Output
Hello, welcome to React!
⚠️

Common Pitfalls

Common mistakes include:

  • Using lowercase names for components, which React treats as HTML tags.
  • Not returning JSX or returning multiple elements without wrapping them in a parent element.
  • Forgetting to import React in older React versions (before 17).

Always start component names with a capital letter and return a single JSX element or use fragments.

jsx
/* Wrong: lowercase component name */
function greeting() {
  return <h1>Hello</h1>;
}

/* Right: capitalized component name */
function Greeting() {
  return <h1>Hello</h1>;
}
📊

Quick Reference

ConceptDescription
Component NameMust start with a capital letter
Return ValueJSX describing UI
JSXLooks like HTML but used in JavaScript
Single ParentJSX must have one root element or use fragments
ExportUse export default to use component elsewhere

Key Takeaways

Create React components as functions returning JSX with a capitalized name.
JSX looks like HTML but is written inside JavaScript to describe UI elements.
Always return a single root element or use React fragments to wrap multiple elements.
Component names starting with lowercase letters are treated as HTML tags and won't work as components.
Export your component to use it in other parts of your app.