Skip to content
Build and Publish Your Own React NPM Package!

React Components Explained Clearly (No Frameworks Needed)

React component is a JavaScript function or class that accepts a single argument called props and returns an element (UI).

React component
syntax

React components return a single user interface

What Exactly Are Props in React?

React props are parameters used to pass arguments (objects) to components. You can use props to pass any JavaScript data type to your component, such as strings, Booleans, and objects.

Here’s an example:

function MyBio(props) {
return <h1>My name is {props.firstName}.</h1>;
}

The code in the snippet above is a function component that accepts a single argument (props) and returns a React element.

How to Invoke React Components

There are four common ways to invoke React components:

  • without props
  • with props
  • with variables
  • with the dot notation

Invoking components without props

You can invoke a component without passing any argument (props) into it.

Here’s an example:

function MyBio() {
return <h1>My name is Oluwatobi.</h1>;
}
<MyBio />;

The snippet above used the <MyBio /> component tag—without any props—to invoke MyBio component.

Invoking components with props

Suppose you wish to pass some arguments into a component. In such a case, invoke the component like so:

function MyBio(props) {
return <h1>My name is {props.firstName}.</h1>;
}
<MyBio firstName="Oluwatobi" />;

The snippet above used <MyBio firstName="Oluwatobi" /> component tag to invoke MyBio component with firstName="Oluwatobi" passed in as an argument to the props parameter.

Invoking components with variables

React allows variables that begin with an uppercase name to be used as component tags.

Here’s an example:

// Define a component inside a variable:
const FirstName = function (props) {
return <h1>My first name is {props.firstName}.</h1>;
};
// Invoke the FirstName component:
<FirstName firstName="Oluwatobi" />;

The snippet above used the <FirstName firstName="Oluwatobi" /> component tag to inform React to:

  • Invoke the FirstName variable’s component and pass in firstName="Oluwatobi" as its props argument.

Invoking components with the dot notation

Suppose your component is inside an object. In that case, use the dot notation to invoke it.

Here’s an example:

// Define two components inside an object:
const MyBio = {
FirstName: function (props) {
return <h1>My first name is {props.firstName}.</h1>;
},
LastName: function (props) {
return <h1>My last name is {props.lastName}.</h1>;
},
};
// Invoke the LastName component:
<MyBio.LastName lastName="Sofela" />;

The snippet above used the <MyBio.LastName lastName="Sofela" /> component tag to inform React to:

  • Invoke MyBio object’s LastName component and pass in lastName="Sofela" as its props argument.

Important Things to Know About React Components

Here are essential facts to remember when using React components.

1. Use the Pascal case naming convention for your components

Always capitalize the first letter of your component’s name (PascalCase). Otherwise, it will not work because React will interpret its invocation as an HTML tag.

React component tag example

<Div />

React will read the tag in the snippet above as a React component tag because it begins with an uppercase letter. So, at build time, compilers will compile (convert) the component tag above to a React.createElement(Div) JavaScript call where the Div text references the Div component you’ve defined in your JavaScript file.

HTML component tag example

<div />

React will interpret the tag in the snippet above as an HTML component tag because it begins with a lowercase letter. So, at build time, compilers will convert the HTML tag above to a React.createElement("div") JavaScript call where the div string represents the built-in browser HTML div tag.

2. Bracket notation expressions do not work as React component tags

Consider the following snippet:

// Define a component:
function FirstName(props) {
return <div>My first name is {props.firstName}.</div>;
}
// Define another component:
function LastName(props) {
return <div>My last name is {props.lastName}</div>;
}
// Define a third component:
function MyBio(props) {
// Assign FirstName and LastName components to two different properties:
const bioComponents = {
firstNameComponent: FirstName,
lastNameComponent: LastName
};
// Use bracket notation expression to specify the bio component React should render:
return (
// Wrong! A component tag cannot be a bracket notation expression.
<bioComponents[props.componentName]
firstNameText={props.firstName}
lastNameText={props.lastName}
/>
);
}
// Render MyBio component to the root DOM:
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<MyBio componentName="lastNameComponent" lastName="Sofela" />);

When you run the script above, React will throw a SyntaxError because we incorrectly used a bracket notation expression as its component tag.

The appropriate way to use a bracket notation expression to express the name of a component tag is to set it as a variable.

3. Bracket notation expressions in variables work as React component tags

Suppose you wish to use a bracket notation expression to express the name of a component tag. In such a case, assign that expression to a variable that begins with an uppercase name.

Here’s an example:

// Define a component:
function FirstName(props) {
return <div>My first name is {props.firstName}.</div>;
}
// Define another component:
function LastName(props) {
return <div>My last name is {props.lastName}</div>;
}
// Define a third component:
function MyBio(props) {
// Assign FirstName and LastName components to two different properties:
const bioComponents = {
firstNameComponent: FirstName,
lastNameComponent: LastName,
};
// Use bracket notation expression to assign a bio component to a variable:
const SelectedBioComponent = bioComponents[props.componentName];
// Use a variable to specify the component React should render:
return (
// Correct! A component tag can be a capitalized variable.
<SelectedBioComponent
firstName={props.firstName}
lastName={props.lastName}
/>
);
}
// Render MyBio component to the root DOM:
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<MyBio componentName="lastNameComponent" lastName="Sofela" />);

When you run the script above, React will render the MyBio component correctly because it uses an appropriately named variable as its component tag.

4. Make your components pure

React components work best as pure functions. It is bad practice for React components to read or mutate external states (variables or objects). In fact, React, by default, assumes that your component is pure. It expects every component to return the same UI for the same props input. So, always ensure your component is pure by reading or mutating only within its scope.

Example 1: Impure React component

let totalPals = 6;
function MyFriends() {
totalPals = totalPals + 1;
return <p>I now have {totalPals} friends.</p>;
}

MyFriends is an impure component because it contains code (totalPals) that mutates an external state—which gives MyFriends some side effects.

Example 2: Pure React component

function MyFriends({ totalPals }) {
return <p>I now have {totalPals} friends.</p>;
}

MyFriends is a pure component because:

  1. It does not modify or depend on any external state. All external data the component uses gets received as props. They are not directly referenced internally. Therefore, what you see within is what you get—no strings attached. The returned UI depends only on its internal props (or variables), so you do not need to look for external conditions (states) that might impact the component’s effective operation as all activities happen within.
  2. The same props input always produces the same user interface. So, if you provide a { totalPals: 7 } props, you will always get a <p>I now have 7 friends.</p> element.

5. Define components at your file’s top level

Always create components at the top level of your file. Nesting a component inside another slows down your application and causes bugs.

In other words, never create a component within another one like this:

function FirstComponent() {
function SecondComponent() {
return <p>Sofela is my last name.</p>;
}
return (
<div>
<h1>My first name is Oluwatobi.</h1>
<SecondComponent />
</div>
);
}

Instead, define all components at your file’s top level as follows:

function FirstComponent() {
return (
<div>
<h1>My first name is Oluwatobi.</h1>
<SecondComponent />
</div>
);
}
function SecondComponent() {
return <p>Sofela is my last name.</p>;
}

Splitting long components into smaller chunks is an excellent way to make individual parts easy to read, manage, and reuse. Let’s discuss more about this practice.

Creating Reusable React Components

Suppose you have a component with elements you wish to reuse. In that case, splitting such components into smaller chunks is best. You can then separate the extracts into individual files.

The issue with rigid components

Consider the following BlogPost component:

BlogPost.js
function BlogPost(props) {
return (
<article>
<header>
<h1>Special Post Title</h1>
<p>A subtitle for this special post</p>
<div>
<span>Author Name</span>
<span></span>
<span>Mar 25, 2025</span>
</div>
</header>
<section className="featured-image">
<img
src={props.imageData.url}
alt={props.imageData.name}
title={props.imageData.description}
/>
</section>
<section className="post">
<h2>Introduction</h2>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas
porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies,
purus lectus malesuada libero, sit amet commodo magna eros quis urna.
</p>
<p>
Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque
habitant morbi tristique senectus et netus et malesuada fames ac
turpis egestas.
</p>
<h2>The Substance</h2>
<p>
Mauris et orci. Aenean nec lorem. In porttitor. Donec laoreet nonummy
augue.
</p>
<p>
Suspendisse dui purus, scelerisque at, vulputate vitae, pretium
mattis, nunc. Mauris eget neque at sem venenatis eleifend. Ut nonummy.
</p>
<p>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas
porttitor congue massa.
</p>
<p>
Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada
libero, sit amet commodo magna eros quis urna. Proin pharetra nonummy
pede.
</p>
</section>
</article>
);
}
const randomImage = {
url: "https://picsum.photos/854/480",
name: "Random Image",
description: "Get a new image each time you refresh your browser.",
};
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<BlogPost imageData={randomImage} />);

The snippet above programmed the BlogPost component to render an article element containing a header, featured image, and post UIs.

The issue with BlogPost’s definition is that it is difficult to reuse its nested elements.

For instance, suppose you want to reuse the header in a different project. In such a case, you must duplicate or rewrite the code because its definition in BlogPost discourages reusability.

A better way to define the BlogPost component is to split its reusable parts into separate files. By so doing, you will have a palette of reusable components that will save you a considerable amount of coding time, especially in larger projects.

How to split rigid components into reusable chunks

The first step in splitting a rigid or complex component into reusable components is identifying the element you can extract from it.

For instance, considering the BlogPost above, we can extract the header, featured image, and post elements into separate components. Let’s discuss the required steps.

  1. Create a new project directory

    Terminal window
    mkdir codesweetly-blog-001

    Afterward, navigate to your project directory using the command line.

    Terminal window
    cd path/to/codesweetly-blog-001
  2. Install React and ReactDOM

    Terminal window
    npm install react react-dom
    • The react package is a library containing React’s core functionality for creating React components.
    • The react-dom API provides the required methods to use React with the DOM.
  3. Create the web page

    Create an HTML page:

    Terminal window
    touch index.html

    Afterward, open the new file and add your HTML code:

    index.html
    <!DOCTYPE html>
    <html lang="en-US">
    <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>CodeSweetly Blog</title>
    </head>
    <body>
    <!-- A main container created for React to manage -->
    <main id="root"></main>
    <!-- Load your React component -->
    <script type="module" src="./BlogPost.js"></script>
    </body>
    </html>

    The snippet above created a <main> container—inside which we want React to display and manage a blog post user interface. In other words, the <main> element represents the website’s section you want React to manage.

    At the same time, we used the script tag to import our blog post component (which we will create in the following section).

  4. Create the BlogPost component

    First, create a file for your component:

    Terminal window
    touch BlogPost.js

    Then, open your BlogPost.js file and define the BlogPost component:

    BlogPost.js
    import ReactDOM from "react-dom/client";
    function BlogPost(props) {
    return (
    <article>
    <header>
    <h1>Special Post Title</h1>
    <p>A subtitle for this special post</p>
    <div>
    <span>Author Name</span>
    <span></span>
    <span>Mar 25, 2025</span>
    </div>
    </header>
    <section className="featured-image">
    <img
    src={props.imageData.url}
    alt={props.imageData.name}
    title={props.imageData.description}
    />
    </section>
    <section className="post">
    <h2>Introduction</h2>
    <p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas
    porttitor congue massa. Fusce posuere, magna sed pulvinar
    ultricies, purus lectus malesuada libero, sit amet commodo magna
    eros quis urna.
    </p>
    <p>
    Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus.
    Pellentesque habitant morbi tristique senectus et netus et
    malesuada fames ac turpis egestas.
    </p>
    <h2>The Substance</h2>
    <p>
    Mauris et orci. Aenean nec lorem. In porttitor. Donec laoreet
    nonummy augue.
    </p>
    <p>
    Suspendisse dui purus, scelerisque at, vulputate vitae, pretium
    mattis, nunc. Mauris eget neque at sem venenatis eleifend. Ut
    nonummy.
    </p>
    <p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas
    porttitor congue massa.
    </p>
    <p>
    Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada
    libero, sit amet commodo magna eros quis urna. Proin pharetra
    nonummy pede.
    </p>
    </section>
    </article>
    );
    }
    const randomImage = {
    url: "https://picsum.photos/854/480",
    name: "Random Image",
    description: "Get a new image each time you refresh your browser.",
    };
    const root = ReactDOM.createRoot(document.getElementById("root"));
    root.render(<BlogPost imageData={randomImage} />);

    Remember that we aim to split the rigid component above into reusable chunks. So, let’s begin by extracting the header.

  5. Create the Header component

    Create a new file called Header.js.

    Terminal window
    touch Header.js

    Open the Header.js file and extract into it the <header> element from the BlogPost component:

    Header.js
    export default function Header() {
    return (
    <header>
    <h1>Special Post Title</h1>
    <p>A subtitle for this special post</p>
    <div>
    <span>Author Name</span>
    <span></span>
    <span>Mar 25, 2025</span>
    </div>
    </header>
    );
    }

    Your BlogPost.js file should now look like this:

    BlogPost.js
    import ReactDOM from "react-dom/client";
    function BlogPost(props) {
    return (
    <article>
    <section className="featured-image">
    <img
    src={props.imageData.url}
    alt={props.imageData.name}
    title={props.imageData.description}
    />
    </section>
    <section className="post">
    <h2>Introduction</h2>
    <p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas
    porttitor congue massa. Fusce posuere, magna sed pulvinar
    ultricies, purus lectus malesuada libero, sit amet commodo magna
    eros quis urna.
    </p>
    <p>
    Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus.
    Pellentesque habitant morbi tristique senectus et netus et
    malesuada fames ac turpis egestas.
    </p>
    <h2>The Substance</h2>
    <p>
    Mauris et orci. Aenean nec lorem. In porttitor. Donec laoreet
    nonummy augue.
    </p>
    <p>
    Suspendisse dui purus, scelerisque at, vulputate vitae, pretium
    mattis, nunc. Mauris eget neque at sem venenatis eleifend. Ut
    nonummy.
    </p>
    <p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas
    porttitor congue massa.
    </p>
    <p>
    Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada
    libero, sit amet commodo magna eros quis urna. Proin pharetra
    nonummy pede.
    </p>
    </section>
    </article>
    );
    }
    const randomImage = {
    url: "https://picsum.photos/854/480",
    name: "Random Image",
    description: "Get a new image each time you refresh your browser.",
    };
    const root = ReactDOM.createRoot(document.getElementById("root"));
    root.render(<BlogPost imageData={randomImage} />);
  6. Create the FeaturedImage component

    Create a new file called FeaturedImage.js.

    Terminal window
    touch FeaturedImage.js

    Open the FeaturedImage.js file and extract into it the featured-image element from the BlogPost component:

    FeaturedImage.js
    export default function FeaturedImage(props) {
    return (
    <section className="featured-image">
    <img
    src={props.imageData.url}
    alt={props.imageData.name}
    title={props.imageData.description}
    />
    </section>
    );
    }

    Your BlogPost.js file should now look like this:

    BlogPost.js
    import ReactDOM from "react-dom/client";
    function BlogPost(props) {
    return (
    <article>
    <section className="post">
    <h2>Introduction</h2>
    <p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas
    porttitor congue massa. Fusce posuere, magna sed pulvinar
    ultricies, purus lectus malesuada libero, sit amet commodo magna
    eros quis urna.
    </p>
    <p>
    Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus.
    Pellentesque habitant morbi tristique senectus et netus et
    malesuada fames ac turpis egestas.
    </p>
    <h2>The Substance</h2>
    <p>
    Mauris et orci. Aenean nec lorem. In porttitor. Donec laoreet
    nonummy augue.
    </p>
    <p>
    Suspendisse dui purus, scelerisque at, vulputate vitae, pretium
    mattis, nunc. Mauris eget neque at sem venenatis eleifend. Ut
    nonummy.
    </p>
    <p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas
    porttitor congue massa.
    </p>
    <p>
    Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada
    libero, sit amet commodo magna eros quis urna. Proin pharetra
    nonummy pede.
    </p>
    </section>
    </article>
    );
    }
    const randomImage = {
    url: "https://picsum.photos/854/480",
    name: "Random Image",
    description: "Get a new image each time you refresh your browser.",
    };
    const root = ReactDOM.createRoot(document.getElementById("root"));
    root.render(<BlogPost imageData={randomImage} />);
  7. Create the Post component

    Create a new file called Post.js.

    Terminal window
    touch Post.js

    Open the Post.js file and extract into it the post element from the BlogPost component:

    Post.js
    export default function Post() {
    return (
    <section className="post">
    <h2>Introduction</h2>
    <p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas
    porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies,
    purus lectus malesuada libero, sit amet commodo magna eros quis urna.
    </p>
    <p>
    Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus.
    Pellentesque habitant morbi tristique senectus et netus et malesuada
    fames ac turpis egestas.
    </p>
    <h2>The Substance</h2>
    <p>
    Mauris et orci. Aenean nec lorem. In porttitor. Donec laoreet nonummy
    augue.
    </p>
    <p>
    Suspendisse dui purus, scelerisque at, vulputate vitae, pretium
    mattis, nunc. Mauris eget neque at sem venenatis eleifend. Ut
    nonummy.
    </p>
    <p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas
    porttitor congue massa.
    </p>
    <p>
    Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada
    libero, sit amet commodo magna eros quis urna. Proin pharetra nonummy
    pede.
    </p>
    </section>
    );
    }

    Your BlogPost.js file should now look like this:

    BlogPost.js
    import ReactDOM from "react-dom/client";
    function BlogPost(props) {
    return <article></article>;
    }
    const randomImage = {
    url: "https://picsum.photos/854/480",
    name: "Random Image",
    description: "Get a new image each time you refresh your browser.",
    };
    const root = ReactDOM.createRoot(document.getElementById("root"));
    root.render(<BlogPost imageData={randomImage} />);
  8. Import your extracted components into the BlogPost.js file

    Import the Header, FeaturedImage, and Post components into your BlogPost.js file and invoke them as follows:

    BlogPost.js
    import ReactDOM from "react-dom/client";
    import Header from "./Header.js";
    import FeaturedImage from "./FeaturedImage.js";
    import Post from "./Post.js";
    function BlogPost(props) {
    return (
    <article>
    <Header />
    <FeaturedImage imageData={randomImage} />
    <Post />
    </article>
    );
    }
    const randomImage = {
    url: "https://picsum.photos/854/480",
    name: "Random Image",
    description: "Get a new image each time you refresh your browser.",
    };
    const root = ReactDOM.createRoot(document.getElementById("root"));
    root.render(<BlogPost imageData={randomImage} />);

    Let’s also make the BlogPost component a pure function by moving the randomImage object into it:

    BlogPost.js
    import ReactDOM from "react-dom/client";
    import Header from "./Header.js";
    import FeaturedImage from "./FeaturedImage.js";
    import Post from "./Post.js";
    function BlogPost(props) {
    const randomImage = {
    url: "https://picsum.photos/854/480",
    name: "Random Image",
    description: "Get a new image each time you refresh your browser.",
    };
    return (
    <article>
    <Header />
    <FeaturedImage imageData={randomImage} />
    <Post />
    </article>
    );
    }
    const root = ReactDOM.createRoot(document.getElementById("root"));
    root.render(<BlogPost imageData={randomImage} />);

    BlogPost’s invocator no longer needs the imageData props, so let’s update it:

    BlogPost.js
    import ReactDOM from "react-dom/client";
    import Header from "./Header.js";
    import FeaturedImage from "./FeaturedImage.js";
    import Post from "./Post.js";
    function BlogPost() {
    const randomImage = {
    url: "https://picsum.photos/854/480",
    name: "Random Image",
    description: "Get a new image each time you refresh your browser.",
    };
    return (
    <article>
    <Header />
    <FeaturedImage imageData={randomImage} />
    <Post />
    </article>
    );
    }
    const root = ReactDOM.createRoot(document.getElementById("root"));
    root.render(<BlogPost />);

    And like magic, we’ve cleaned up the BostPost component by making the header, featured image, and post UIs reusable components that any module can import and use.

  9. Run your application

    Install the Parcel app building tool so that you can use it to bundle all your modules and make your code browser compatible.

    Terminal window
    npm install --save-dev parcel

    After installing Parcel, use it to build and run your app from your terminal:

    Terminal window
    npx parcel ./index.html

    The snippet above tells Parcel to build the app from the project’s entry point (index.html).

    After the build step, Parcel will use its built-in development server to run your app automatically. So, open http://localhost:1234 in your browser to see your app running live!

And that’s it!

You’ve successfully extracted the reusable portion of the BlogPost component into individual parts that are easier to read, manage, and reuse!

Tips on creating reusable React components

  • React developers typically use one file for just one component, making each UI easy to reuse in multiple projects.
  • Capitalizing the first letter of your component’s filename makes it faster to differentiate a React component file from a regular JavaScript file.
  • Avoid default exports of unnamed function components. It is best to default export only named components.
  • It is common to use a components directory to store a project’s component files for effective organization. In other words, you can create a components folder to store the BlogPost, Header, FeaturedImage, and Post components. When you do so, remember to update each file’s relative path. For instance, instead of ./BlogPost.js in your HTML file, you will use ./components/BlogPost.js.
  • A common practice is to use an App component as the parent (root component) of all other components in a project while using an index.js (the entry script) to render the App component to the root DOM. For instance, you can rename the BlogPost file and component to App and create a new index.js file for rendering as follows:
App.js
import Header from "./Header.js";
import FeaturedImage from "./FeaturedImage.js";
import Post from "./Post.js";
export default function App() {
const randomImage = {
url: "https://picsum.photos/854/480",
name: "Random Image",
description: "Get a new image each time you refresh your browser.",
};
return (
<article>
<Header />
<FeaturedImage imageData={randomImage} />
<Post />
</article>
);
}

Time to Practice with Components ‍️️‍️‍️🤸‍♂️🏋️‍♀️🏊‍♀️

Here is your moment to practice the concepts you’ve learned on components.

  • Render four (or more) checkboxes to the webpage without using JavaScript loops. Ensure each checkbox has its associated text next to it. Here’s an example of the expected outcome:

Four
checkboxes

Example of checkboxes created with React components

Show the solution

Below is one feasible way to render multiple checkboxes to the webpage without using JavaScript loops.

  1. Create a new project directory

    Terminal window
    mkdir codesweetly-checkboxes-001

    Navigate to your project directory using the command line.

    Terminal window
    cd path/to/codesweetly-checkboxes-001
  2. Install React and ReactDOM

    Terminal window
    npm install react react-dom
  3. Create the web page

    Create an HTML page:

    Terminal window
    touch index.html

    Afterward, open the new file and add the HTML code containing the root element and the entry script.

    index.html
    <!DOCTYPE html>
    <html lang="en-US">
    <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>CodeSweetly Checkboxes</title>
    </head>
    <body>
    <main id="root"></main>
    <script type="module" src="index.js"></script>
    </body>
    </html>
  4. Create a components directory

    Create a new components directory in your project’s root folder.

    Terminal window
    mkdir components
  5. Create the Checkbox component

    Create a new file called Checkbox.js.

    Terminal window
    touch components/Checkbox.js

    Open the Checkbox.js file and create a Checkbox component that returns a <div> element containing an <input> element and a <label> element:

    Checkbox.js
    export default function Checkbox({ id, text }) {
    return (
    <div>
    <input type="checkbox" id={id} name="techConcept" value={text} />
    <label htmlFor={id}>{text}</label>
    </div>
    );
    }
  6. Create the root component

    Create a file for your App component:

    Terminal window
    touch components/App.js

    Open the root component file (App.js) and create an App component that returns a <fieldset> element containing a <legend> element and four <Checkbox> components:

    App.js
    import Checkbox from "./Checkbox.js";
    export default function App() {
    return (
    <fieldset>
    <legend>
    <strong>What tech concept are you learning?</strong>
    </legend>
    <Checkbox id="javascript" text="JavaScript" />
    <Checkbox id="css" text="CSS" />
    <Checkbox id="html" text="HTML" />
    <Checkbox id="react" text="React" />
    </fieldset>
    );
    }
  7. Create the entry script

    Create a file to render your components to the root DOM.

    Terminal window
    touch index.js

    Open the index.js file and render the App component to the DOM:

    index.js
    import ReactDOM from "react-dom/client";
    import App from "./components/App";
    const root = ReactDOM.createRoot(document.getElementById("root"));
    root.render(<App />);
  8. Run your application

    Install Parcel so that you can use it to bundle and transpile your dependencies.

    Terminal window
    npm install --save-dev parcel

    After installing Parcel, use it to build and run your app from your terminal:

    Terminal window
    npx parcel index.html

The checkbox app without reusable components

Suppose you did not separate the checkbox user interface into an individual component. In that case, your App component would look like this:

App.js
export default function App() {
return (
<fieldset>
<legend>
<strong>What tech concept are you learning?</strong>
</legend>
<div>
<input
type="checkbox"
id="javascript"
name="techConcept"
value="JavaScript"
/>
<label htmlFor="javascript">JavaScript</label>
</div>
<div>
<input type="checkbox" id="css" name="techConcept" value="CSS" />
<label htmlFor="css">CSS</label>
</div>
<div>
<input type="checkbox" id="html" name="techConcept" value="HTML" />
<label htmlFor="html">HTML</label>
</div>
<div>
<input type="checkbox" id="react" name="techConcept" value="React" />
<label htmlFor="react">React</label>
</div>
</fieldset>
);
}

You can see how long-winded the App component looks. Such is the disadvantage of not splitting your UI into reusable components.

Stay Tuned for the State Tutorial

States in React are essential for storing a component’s UI values. Watch out for the tutorial, which will explain states clearly. You can also sign up for the CodeSweetly newsletter to receive an email notification once the guide is published.