npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-hook-checkbox

v1.0.42

Published

Checkbox Hook for React

Downloads

22

Readme

React Hook Checkbox

An easy to use, all-in-one, minimal setup, React Hook for checkboxes.

npm npm bundlephobia standard scrutinizer codecov

Features

Demo

Table of Contents

Quickstart | API | Usage | FAQ

Install

npm install react-hook-checkbox

Quickstart

import * as React from "react";

import { useCheckbox } from "react-hook-checkbox";

const config = {
  name: "Shopping List",
  options: [{
    name: "Eggs",
  }, {
    name: "Milk",
  }, {
    name: "Cheese",
  }]
};

const MyPage = () => {

  const [myCheckbox] = useCheckbox(config);

  return (
    <>
      {myCheckbox.options.map((option, index) => {
        return (
          <label key={index} style={{ marginLeft: "15px" }}>
            <input
              type="checkbox"
              checked={option.isSelected}
              onChange={() => option.select()}
            />
            {option.name}
          </label>
        );
      })}
    </>
  );
};

export default MyPage;

API

const checkboxConfig = {...}

Checkboxes are built with a user-provided configuration object hereinafter referred to as checkboxConfig. The checkboxConfig accepts the following parameters:

  • name - the name of the checkbox. Defaults to "".
  • options - any child checkboxes. Defaults to [].
  • properties - properties provided to the checkbox. Defaults to undefined,
  • isSelected - true/false if the checkbox is selected. Defaults to false.

* all of these paramers are optional

const [myList, setMyList] = useCheckbox(checkboxConfig)

Creates the checkboxes from the provided checkboxConfig. Returns a React hook.

All checkboxes (myList and its options) share the same properties/functions as described below:

Properties:

  • .name - name of the checkbox
  • .options - arrary of any child checkboxes. [] if there are none.
  • .properties - properties provided to the checkbox.
  • .isSelected - true/false if checkbox is selected.
  • .ref - refrence to the parent checkbox. undefined if there's no parent.

Note: Remember to follow React's rule's of Hooks when working with .properties.

Functions:

.setCheckbox(config)

Resets and creates a new checkbox on from the provided configuration.
Accepts a checkboxConfig.

.setOptions(options)

Resets the .options to a new set of options from the provided configuration.
Accepts a checkboxConfig[].

.addOption(option)

Adds a child checkbox to .options from the provided configuration.
Accepts a checkboxConfig.

.setIsSelected(isSelected)

Sets the .isSelected of the checkbox.
Accepts a boolean.

.setProperties(properties)

Sets the .properties of the checkbox.
Accepts an any.

.setName(name)

Sets the .name of the checkbox.
Accepts a string.

.getSelectedOptions()

Returns an array of all child checkboxes in which .isSelected is true.

.isIndeterminate()

Returns true/false if the checkbox is indeterminate.

.isAllSelected()

Returns true/false if .isSelected of all child checkboxes is true.

.isAnySelected()

Returns true/false if .isSelected of any child checkbox is true.

.removeOption()

Removes a checkbox from the parent checkbox's .options.

.select()

Selects a single checkbox, inverting the current .isSelected.

Usage

Setting the initial state:

const config = {
  name: 'List',
  isSelected: false,
  properties: { myProperties: "hello world!"},
  options: [{
    name: 'Option 1',
    isSelected: true,
    properties: { myProperties: "fizz!"}
  }, {
    name: 'Option 2',
    isSelected: false,
    properties: { myProperties: "buzz!"}
  }, {
    name: 'Option 3',
    isSelected: true,
    properties: { myProperties: "fizzbuzz!"}
  }]
};

const MyPage = () => {

  const [myCheckbox] = useCheckbox(config);

  return (
    <>
      <p>Will say "FizzBuzz":</p>
      {myCheckbox.options[2].properties.myProperties}
    </>
  );
};

Utilizing default values:

const MyPage = () => {

  // since all paramters are options `{}` is valid use of `useCheckbox()`
  const [myCheckbox] = useCheckbox({});

  return (
    <>
      <p> name is "" by default </p>
      {myCheckbox.name}

      <p> isSelected is false by default </p>
      {myCheckbox.isSelected ? "true" : "false"}
    </>
  );
};

Setting name, options, properties and adding/removing options:

const MyPage = () => {

  const [myCheckbox] = useCheckbox(config);

  const option = {
    name: "new option"
  }

  const options = [{
    name: "new option 1"
  }, {
    name: "new option 2"
  }]

  const newProperties = { myProperties: "new property" };

  // display new list in console on rerender
  console.log(myCheckbox);

  return (
    <>
      <button onClick={() => myCheckbox.setName("new name")}>Set Name</button>
      <button onClick={() => myCheckbox.setProperties(newProperties)}>Set Properties</button>
      <button onClick={() => myCheckbox.addOption(option)}>Add Option</button>
      <button onClick={() => myCheckbox.setOptions(options)}>Set Option</button>
      <button onClick={() => myCheckbox.options[0].removeOption()}>Remove First Option</button>
    </>
  );
};

Display a single set of checkboxes:

const MyPage = () => {

  const [myCheckbox] = useCheckbox(config);

  return (
    <>
      {myCheckbox.options.map((option, index) => {
        return (
          <label key={index} style={{ marginLeft: "15px" }}>
            <input
              type="checkbox"
              checked={option.isSelected}
              onChange={() => option.select()}
            />
            {option.name}
          </label>
        );
      })}
    </>
  );
};

Display all checkboxes recursively:

const MyPage = () => {

  const [myCheckbox] = useCheckbox(config);

  const displayCheckboxex = (checkbox) => {
    return (
      <div style={{ margin: "10px" }}>
        <input
          type="checkbox"
          checked={checkbox.isSelected}
          onChange={() => checkbox.select()}
          ref={input => {
            if (input) {
              input.indeterminate = checkbox.isIndeterminate();
            }
          }}
        />
        {checkbox.name}
        {checkbox.options.map((option, index) => {
          return (
            <div key={index} style={{ marginLeft: "15px" }}>
              {myCheckbox.options.length ?
                displayCheckboxex(option)
                :
                <></>
              }
            </div>
          );
        })}
      </div>
    )
  }

  return (
    <>
      {displayCheckboxex(myCheckbox)}
    </>
  );
};

Usage with TypeScript:

type MyType = string;

const config: CheckboxConfig<MyType> = {
  properties: "fizzbuzz"
};

const MyPage = () => {

  const [myCheckbox] = useCheckbox<MyType>(config);

  return (
    <>
      {myCheckbox.properties}
    </>
  );
};

FAQ

Q: I found a bug, have a suggestion/issue, or need help!

Please raise an issue on the Github repository.

Q: Are you looking for contributors?

Yes! If you'd like to contribute to the project, please raise a pull request.

Q: How can I say thanks?

Feel free to send me an email: [email protected]