Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to create a checkbox in ReactJS

Introduction

Hello there, budding programmers! Today, we're going to embark on an exciting journey into the world of ReactJS, a popular JavaScript library for building user interfaces. Our journey's destination? The creation of a checkbox, a simple yet important user interface component that you're likely to encounter in many web applications.

Think of the checkbox as an on-off switch, a bit like the light switches in your house. You can click it to turn it "on" (or check it), or click it again to turn it "off" (or uncheck it). The magic of programming lies in harnessing these simple interactions to perform more complex tasks. But, just like building a house, we need to lay the foundation first.

Before we dive in, let's clarify a couple of terminologies. In the world of coding, a "library" is a collection of pre-written code that developers can use to save time and effort. You can think of it as a toolbox filled with different tools, each designed to perform a specific task. For instance, ReactJS is a library that provides tools for building user interfaces.

Setting Up Your React App

Before we can create a checkbox, we need to have a React app to put it in. Setting up a React app might seem daunting if you're new to programming, but don't worry; it's much simpler than it sounds.

We're going to use a tool called "Create React App". It's a command-line tool provided by the creators of React that sets up a new React app with a single command. It's like a magic spell that conjures up a new app out of thin air!

Here's how you use it:

npx create-react-app checkbox-tutorial

This command creates a new React app in a directory called "checkbox-tutorial". You can think of a directory as a folder on your computer where your app's files live. Once the command finishes, navigate into your new app's directory with this command:

cd checkbox-tutorial

The Anatomy of a Checkbox

A checkbox in HTML is represented by the <input> element with the type attribute set to checkbox. Here's what it looks like:

<input type="checkbox">

However, in React, we don't use HTML directly. Instead, we use JSX, a syntax extension for JavaScript that allows us to write HTML-like code in our JavaScript files. JSX stands for JavaScript XML, but don't worry about the 'XML' part for now. Just think of JSX as a way to write HTML in your JavaScript code.

A checkbox in JSX looks very similar to its HTML counterpart:

<input type="checkbox" />

Notice the / at the end of the tag. This is one of the differences between HTML and JSX. In JSX, all tags must be closed, even if they don't have a matching closing tag in HTML.

Creating a Checkbox in React

Now that we know what a checkbox looks like, let's create one in our React app. First, open up the App.js file in your app's src directory. This is the main component of your app.

Replace the contents of App.js with the following code:

import React from 'react';

function App() {
  return (
    <div className="App">
      <input type="checkbox" />
    </div>
  );
}

export default App;

This code defines a function named App that returns a JSX expression. This expression consists of a <div> element with a class of "App" and a single checkbox inside it. The export default App; line at the end makes our App function available for other files to import.

If you run your app now with the command npm start, you should see a checkbox on the page.

Handling Checkbox State

Our checkbox is visible, but it doesn't do anything yet. To make it interactive, we need to introduce the concept of "state". In React, state refers to data that can change over time and affect what your app displays.

Imagine your app as a living creature. Its state would be things like its mood, energy level, or hunger – things that can change over time and affect the creature's behavior.

To handle state in our checkbox, we'll use a React Hook called useState. Hooks are a feature of React that let you add state and other React features to function components.

Let's update our App function to use useState:

import React, { useState } from 'react';

function App() {
  const [isChecked, setIsChecked] = useState(false);

  return (
    <div className="App">
      <input type="checkbox" />
    </div>
  );
}

export default App;

In the code above, we're using the useState Hook to create a new state variable isChecked and a function setIsChecked to update it. The initial value of isChecked is false, indicating that the checkbox is not checked by default.

Wiring Up the Checkbox

The last step is to wire up our checkbox to the isChecked state variable. We'll do that by setting its checked attribute to the value of isChecked and its onChange attribute to a function that updates isChecked.

Here's the final version of App.js:

import React, { useState } from 'react';

function App() {
  const [isChecked, setIsChecked] = useState(false);

  const handleCheckboxChange = (event) => {
    setIsChecked(event.target.checked);
  };

  return (
    <div className="App">
      <input type="checkbox" checked={isChecked} onChange={handleCheckboxChange} />
    </div>
  );
}

export default App;

In this code, handleCheckboxChange is a function that gets called whenever the checkbox is clicked. It takes an event object as a parameter, which contains information about the event, and uses event.target.checked to get the current checked state of the checkbox.

And that's it! You've now created an interactive checkbox in React. If you start your app and click the checkbox, you'll see that it gets checked and unchecked as expected. Congratulations, you've taken one more step on your coding journey!

Wrapping Up

Creating a checkbox in React might seem like a small task, and in a way, it is. But it's also a stepping stone to more complex React components and concepts. By understanding how a checkbox works, you're well on your way to mastering React and building amazing web applications.

Remember, learning to code is a journey. It might seem challenging at times, but every step you take brings you closer to your destination. Keep exploring, keep experimenting, and most importantly, keep coding. Happy coding!