Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-checkbox-tree

jakezatecky393.7kMIT1.8.0TypeScript support: included

A simple and elegant checkbox tree for React.

react, checkbox, tree

readme

react-checkbox-tree

npm Build Status GitHub license

A simple and elegant checkbox tree for React.

Demo

Usage

Installation

Install the library using your favorite dependency manager:

yarn add react-checkbox-tree

Using npm:

npm install react-checkbox-tree --save

Note – This library makes use of Font Awesome styles and expects them to be loaded in the browser.

Note – Although React 18 should work, our unit tests run against React 17 due to incompatibility with the unit testing tool (Enzyme).

Include CSS

For your convenience, the library's styles can be consumed utilizing one of the following files:

  • node_modules/react-checkbox-tree/lib/react-checkbox-tree.css
  • node_modules/react-checkbox-tree/src/less/react-checkbox-tree.less
  • node_modules/react-checkbox-tree/src/scss/react-checkbox-tree.scss

Either include one of these files in your stylesheets or utilize a CSS loader:

import 'react-checkbox-tree/lib/react-checkbox-tree.css';

Render Component

A quick usage example is included below. Note that the react-checkbox-tree component is controlled. In other words, you must update its checked and expanded properties whenever a change occurs.

import React from 'react';
import CheckboxTree from 'react-checkbox-tree';

const nodes = [{
    value: 'mars',
    label: 'Mars',
    children: [
        { value: 'phobos', label: 'Phobos' },
        { value: 'deimos', label: 'Deimos' },
    ],
}];

class Widget extends React.Component {
    state = {
        checked: [],
        expanded: [],
    };

    render() {
        return (
            <CheckboxTree
                nodes={nodes}
                checked={this.state.checked}
                expanded={this.state.expanded}
                onCheck={checked => this.setState({ checked })}
                onExpand={expanded => this.setState({ expanded })}
            />
        );
    }
}

All node objects must have a unique value. This value is serialized into the checked and expanded arrays and is also used for performance optimizations.

Changing the Default Icons

By default, react-checkbox-tree uses Font Awesome 4 for the various icons that appear in the tree. To utilize Font Awesome 5 icons, simply pass in iconsClass="fa5":

<CheckboxTree
    ...
    iconsClass="fa5"
/>

To change the rendered icons entirely, simply pass in the icons property and override the defaults. Note that you can override as many or as little icons as you like:

<CheckboxTree
    ...
    icons={{
        check: <span className="rct-icon rct-icon-check" />,
        uncheck: <span className="rct-icon rct-icon-uncheck" />,
        halfCheck: <span className="rct-icon rct-icon-half-check" />,
        expandClose: <span className="rct-icon rct-icon-expand-close" />,
        expandOpen: <span className="rct-icon rct-icon-expand-open" />,
        expandAll: <span className="rct-icon rct-icon-expand-all" />,
        collapseAll: <span className="rct-icon rct-icon-collapse-all" />,
        parentClose: <span className="rct-icon rct-icon-parent-close" />,
        parentOpen: <span className="rct-icon rct-icon-parent-open" />,
        leaf: <span className="rct-icon rct-icon-leaf" />,
    }}
/>

If you are using the react-fontawesome library, you can also directly substitute those icons:

import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'

...

<CheckboxTree
    ...
    icons={{
        check: <FontAwesomeIcon className="rct-icon rct-icon-check" icon="check-square" />,
        uncheck: <FontAwesomeIcon className="rct-icon rct-icon-uncheck" icon={['fas', 'square']} />,
        halfCheck: <FontAwesomeIcon className="rct-icon rct-icon-half-check" icon="check-square" />,
        expandClose: <FontAwesomeIcon className="rct-icon rct-icon-expand-close" icon="chevron-right" />,
        expandOpen: <FontAwesomeIcon className="rct-icon rct-icon-expand-open" icon="chevron-down" />,
        expandAll: <FontAwesomeIcon className="rct-icon rct-icon-expand-all" icon="plus-square" />,
        collapseAll: <FontAwesomeIcon className="rct-icon rct-icon-collapse-all" icon="minus-square" />,
        parentClose: <FontAwesomeIcon className="rct-icon rct-icon-parent-close" icon="folder" />,
        parentOpen: <FontAwesomeIcon className="rct-icon rct-icon-parent-open" icon="folder-open" />,
        leaf: <FontAwesomeIcon className="rct-icon rct-icon-leaf-close" icon="file" />
    }}
/>

Utility Functions

In addition to the CheckboxTree component, additional utility functions are available to set the initial state of the tree.

expandNodesToLevel(nodes, targetLevel)

Creates a list of all parent node keys until targetLevel.

Arguments:

  • nodes (Array): The same array of nodes passed into the main CheckboxTree component
  • targetLevel (number): The maximum expansion depth. Use Infinity for maximum depth.

Returns:

  • Array: A list of node keys.

Properties

Property Type Description Default
nodes array Required. Specifies the tree nodes and their children.
checkModel string Specifies which checked nodes should be stored in the checked array. Accepts 'leaf' or 'all'. 'leaf'
checked array An array of checked node values. []
direction string A string that specify whether the direction of the component is left-to-right ('ltr') or right-to-left ('rtl'). 'ltr'
disabled bool If true, the component will be disabled and nodes cannot be checked. false
expandDisabled bool If true, the ability to expand nodes will be disabled. false
expandOnClick bool If true, nodes will be expanded by clicking on labels. Requires a non-empty onClick function. false
expanded array An array of expanded node values. []
icons object An object containing the mappings for the various icons and their components. See Changing the Default Icons. { ... }
iconsClass string A string that specifies which icons class to utilize. Currently, 'fa4' and 'fa5' are supported. 'fa4'
id string A string to be used for the HTML ID of the rendered tree and its nodes. null
lang object An object containing the language mappings for the various text elements. { ... }
name string Optional name for the hidden <input> element. undefined
nameAsArray bool If true, the hidden <input> will encode its values as an array rather than a joined string. false
nativeCheckboxes bool If true, native browser checkboxes will be used instead of pseudo-checkbox icons. false
noCascade bool If true, toggling a parent node will not cascade its check state to its children. false
onlyLeafCheckboxes bool If true, checkboxes will only be shown for leaf nodes. false
optimisticToggle bool If true, toggling a partially-checked node will select all children. If false, it will deselect. true
showExpandAll bool If true, buttons for expanding and collapsing all parent nodes will appear in the tree. false
showNodeIcon bool If true, each node will show a parent or leaf icon. true
showNodeTitle bool If true, the label of each node will become the title of the resulting DOM node. Overridden by node.title. false
onCheck function onCheck handler: function(checked, targetNode) {} () => {}
onClick function onClick handler: function(targetNode) {}. If set, onClick will be called when a node's label has been clicked. () => {}
onExpand function onExpand handler: function(expanded, targetNode) {} () => {}

onCheck and onExpand

Node Properties

Individual nodes within the nodes property can have the following structure:

Property Type Description Default
label mixed Required. The node's label.
value mixed Required. The node's value.
children array An array of child nodes. null
className string A className to add to the node. null
disabled bool Whether the node should be disabled. false
icon mixed A custom icon for the node. null
showCheckbox bool Whether the node should show a checkbox. true
title string A custom title attribute for the node. null

changelog

CHANGELOG

v1.8.0 (2020-08-06)

Other

  • [#329] Add React 18 to the peer dependency list (Note: React 18 is not part of the automatic testing, but should work)

v1.7.3 (2020-05-23)

Bug Fixes

  • [#258]: Fix check behavior on nodes with an empty children array

v1.7.2 (2021-08-09)

Bug Fixes

  • [#281]: Fix accessibility issues with checkbox nodes
  • [#288]: Fix issue with custom checkbox icons appearing when nativeCheckboxes={true}

v1.7.1 (2021-06-08)

Build

  • Fix build issues for default exports

v1.7.0 (2021-06-08)

New Features

  • [#182]: Add direction property to support RTL languages
  • [#211]: Throw an error when nodes have duplicate values
  • [#244]: Add expandNodesToLevel utility

Bug Fixes

  • [#208]: Add missing onCheck argument in TypeScript definition
  • [#248]: Add missing onExpand argument in TypeScript definition

v1.6.0 (2019-12-11)

New Features

  • [#13]: Add checkModel property to specify which nodes should be stored in the checked array (currently "all" and "leaf" supported)
  • [#126]: Add iconsClass property and allow 'fa5' to fully support Font Awesome 5 icons
  • [#171]: Allow parent nodes to have an empty children array

Bug Fixes

  • [#127]: Change TypeScript definition of TreeNode's label property to React.ReactNode to better align with the PropType
  • [#145]: Fix alignment of many React properties to TypeScript typings
  • [#180]: Fix issue where the id property did not apply to the top-level CheckboxTree container

v1.5.0 (2019-01-25)

New Features

  • [#116]: Add id property to specify the DOM ID for the generated tree nodes
  • [#122]: Add label, isLeaf, isParent, parent, treeDepth, and level metadata to the target node of onCheck, onClick, and onExpand handlers

Bug Fixes

  • [#119]: Fix issue where an initially disabled tree could not be enabled after the initial render
  • [#120]: Fix issue where Internet Explorer and Microsoft Edge browsers would fail to update check state when a parent was in a half-check or indeterminate state
  • [#125]: Fix misalignment of TreeNode's label property between PropType and TypeScript definitions

Other

  • [#115]: Add example react-fontawesome usage for the icons prop

v1.4.1 (2018-09-21)

Bug Fixes

  • [#113]: Add missing expandOpen property from TypeScript declaration (...again)

v1.4.0 (2018-09-21)

New Features

  • [#114]: Add rct-node-expanded and rct-node-collapsed classes to expanded and collapsed parent nodes

Bug Fixes

  • [#113]: Add missing expandOpen property from TypeScript declaration

v1.3.1 (2018-09-06)

Bug Fixes

  • [#109]: Fix erroneous PropTypes check for lang property

v1.3.0 (2018-09-05)

New Features

  • [#79]: Add showExpandAll property to give the user the ability to expand or collapse all nodes in the tree
  • [#96]: Add TypeScript definitions
  • [#102]: Add icons property to allow specification of icon components
  • [#103]: Add title node property and showNodeTitle tree property
  • [#108]: Add lang property for language customization

Bug Fixes

  • [#61]: Fix issue where disabled children would be checked if a parent node was checked

Other

  • [#91]: Prevent disconnection between Sass and Less files on build
  • [#97]: Some performance optimizations

v1.2.4 (2018-08-29)

Bug Fixes

  • [#82], [#84]: Fix undefined Crypto API errors in Node environments
  • [#104]: Fix issue where numeric node values could trigger PropType warnings

v1.2.3 (2018-06-23)

Bug Fixes

  • [#81]: Fix render errors for all numeric value types

v1.2.2 (2018-05-24)

Bug Fixes

  • [#89]: Fix misnamed variables in the Less stylesheets
  • [#90]: Coerce NaN types to string when outputting DOM IDs

v1.2.1 (2018-05-10)

Bug Fixes

  • [#87]: Fix issue where passing the onClick property would trigger a warning about unique key prop

v1.2.0 (2018-05-08)

New Features

  • [#68]: Add onClick and expandOnClick properties

Other

  • [#69]: Tree will no longer throw an exception if checked or expanded contains values that do not recursively exist in the nodes property

v1.1.0 (2018-03-31)

New Features

  • [#53]: Add nativeCheckboxes property to allow use of native browser checkboxes instead of pseudo-checkbox icons
  • [#72]: Add the node that triggers onCheck or onExpand as a second parameter to the callback functions
  • [#80]: Add onlyLeafCheckboxes property and support showCheckbox on the node-level

v1.0.2 (2017-10-24)

Bug Fixes

  • [#57]: Fix an issue where node values with spaces in them would cause validation errors

v1.0.1 (2017-09-30)

Dependencies

  • [#54]: Add support for React 16

v1.0.0 (2017-09-21)

New Features

  • [#49]: Add the ability to specify disabled to individual nodes
  • [#50]: Allow node.label to be any valid React node

Usability

  • [#51]: Apply additional background color when a node is active

v0.6.4 (2017-07-22)

Bug Fixes

  • [#42]: Fix npm package not aligning with Git version

v0.6.3 (2017-05-30)

The v0.6.x series will likely be the last series before the v1.0 release. The API is not expected to significantly change, but new features will not be added to pre-1.0 versions.

New Features

  • [#35]: Add disabled and expandDisabled options to <CheckboxTree>

v0.6.2 (2017-05-25)

New Features

  • [#34]: Add noCascade option to decouple parent check state from children

v0.6.1 (2017-05-09)

Other

  • [#33]: Add a prepublish command to ensure that the ./lib folder is built before package is published to npm

v0.6.0 (2017-05-06)

New Features

  • [#32]: Allow customization of className at the node level
  • [#30]: Add showNodeIcon property to optionally remove node icons

Other

  • [#14]: Component performance when rendering and updating a large number of nodes has been significantly increased

v0.5.2 (2017-05-03)

Bug Fixes

  • [#31]: Fix issue where expand buttons would submit a parent form

v0.5.1 (2017-03-21)

New Features

  • [#27]: Add rct-node-leaf and rct-node-parent classes to the TreeNode <li> element

v0.5.0 (2017-03-12)

Breaking Changes

  • [#20]: Remove deprecated title property in nodes (use label instead)

New Features

  • [#2]: Allow customization of icons via CSS
  • [#26]: Allow icon customization at node level

v0.4.2 (2017-02-27)

Bug Fixes

  • [#22]: Remove expand-like behavior on nodes without children
  • [#23]: Fix issue where property validation was not occurring on node items

v0.4.1 (2017-02-15)

Deprecations

  • [#20]: Add support for label in nodes property and deprecate title

New Features

  • [#21]: Add greater accessibility support

v0.4.0 (2017-01-27)

Bug Fixes

  • [#17]: Auto-prefix CSS styles to support older browsers
  • [#18]: Remove unnecessary margin on tree lists

New Features

  • [#15]: Provide optimisticToggle configuration to toggle child nodes optimistically or pessimistically