• This repository has been archived on 27/Nov/2020
  • Stars
    star
    453
  • Rank 96,573 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 7 years ago
  • Updated almost 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Component to build simple, flexible, and accessible toggle components

react-toggled βš›οΈ
react-toggled logo

Component to build simple, flexible, and accessible toggle components


Build Status Code Coverage downloads version MIT License

All Contributors PRs Welcome Chat Code of Conduct

Supports React and Preact size gzip size module formats: umd, cjs, and es

Watch on GitHub Star on GitHub Tweet

The problem

You want a toggle component that's simple and gives you complete control over rendering and state.

This solution

This follows the patterns in downshift to expose an API that renders nothing and simply encapsulates the logic of a toggle component.

Table of Contents

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's dependencies:

npm install --save react-toggled

This package also depends on react and prop-types. Please make sure you have those installed as well.

Note also this library supports preact out of the box. If you are using preact then look in the preact/ folder and use the module you want. You should be able to simply do: import Toggle from 'react-toggled/preact'

Usage

import React from 'react'
import {render} from 'react-dom'
import Toggle from 'react-toggled'

render(
  <Toggle>
    {({on, getTogglerProps}) => (
      <div>
        <button {...getTogglerProps()}>Toggle me</button>
        <div>{on ? 'Toggled On' : 'Toggled Off'}</div>
      </div>
    )}
  </Toggle>,
  document.getElementById('root'),
)

react-toggled is the only component. It doesn't render anything itself, it just calls the child function and renders that. Wrap everything in <Toggle>{/* your function here! */}</Toggle>.

Props:

defaultOn

boolean | defaults to false

The initial on state.

onToggle

function(on: boolean, object: TogglerStateAndHelpers) | optional, no useful default

Called when the toggler is clicked.

  • on: The new on state
  • TogglerStateAndHelpers: the exact same thing you get in your child render prop function.

on

boolean | control prop

react-toggled manages its own state internally and calls your onToggle handler whenever the on state changes. Your child render prop function (read more below) can be used to manipulate this state from within the render function and can likely support many of your use cases.

However, if more control is needed, you can pass the on state as a prop and that state becomes controlled. As soon as this.props.on !== undefined, internally, react-toggled will determine its state based on your prop's value rather than its own internal state. You will be required to keep the state up to date (this is where onToggle comes in really handy), but you can also control the state from anywhere, be that state from other components, redux, react-router, or anywhere else.

Note: This is very similar to how normal controlled components work elsewhere in react (like <input />). If you want to learn more about this concept, you can learn about that from this the "Controlled Components" lecture and exercises from React Training's > Advanced React course.

children

function({}) | required

This is called with an object.

This is where you render whatever you want to based on the state of react-toggled. The function is passed as the child prop: <Toggle>{/* right here*/}</Toggle>

property category type description
on state boolean The current on state of toggle
getTogglerProps prop getter function(props: object) returns the props you should apply to the button element you render. Includes aria- attributes
getInputTogglerProps prop getter function(props: object) returns the props you should apply to the input (checkbox) element you render. Includes aria- attributes
getElementTogglerProps prop getter function(props: object) returns the props you should apply to the element you render. Use this if you are not using a button or inputβ€”for example, a span. Includes aria- attributes
setOn action function() Sets the on state to true
setOff action function() Sets the on state to false
toggle action function() Toggles the on state (i.e. if it's currently true, will set to false)

Examples

Examples exist on codesandbox.io:

If you would like to add an example, follow these steps:

  1. Fork this codesandbox
  2. Make sure your version (under dependencies) is the latest available version.
  3. Update the title and description
  4. Update the code for your example (add some form of documentation to explain what it is)
  5. Add the tag: react-toggled:example

You'll find other examples in the stories/examples folder of the repo. And you'll find a live version of those examples here

Inspiration

I built this while building an example of using glamorous with next.js

Other Solutions

You can implement any of the other solutions using react-toggled, but if you'd prefer to use these out of the box solutions, then that's fine too. There are tons of them, so just checkout npm.

Contributors

Thanks goes to these people (emoji key):

Kent C. Dodds
Kent C. Dodds

πŸ’» πŸ“– πŸš‡ ⚠️
Frank Tan
Frank Tan

πŸ’» πŸ“– ⚠️
Oliver
Oliver

πŸ’»
Jedrzej Lewandowski
Jedrzej Lewandowski

πŸ’»
Ben Slinger
Ben Slinger

πŸ’» ⚠️
Justin Dorfman
Justin Dorfman

πŸ”

This project follows the all-contributors specification. Contributions of any kind welcome!

LICENSE

MIT

More Repositories

1

cross-env

πŸ”€ Cross platform setting of environment scripts
JavaScript
6,313
star
2

match-sorter

Simple, expected, and deterministic best-match sorting of an array in JavaScript
TypeScript
3,719
star
3

advanced-react-patterns

This is the latest advanced react patterns workshop
JavaScript
2,885
star
4

babel-plugin-macros

🎣 Allows you to build simple compile-time libraries
JavaScript
2,622
star
5

react-hooks

Learn React Hooks! 🎣 βš›
JavaScript
2,550
star
6

bookshelf

Build a ReactJS App workshop
JavaScript
2,533
star
7

kentcdodds.com

My personal website
MDX
2,143
star
8

use-deep-compare-effect

πŸ‹ It's react's useEffect hook, except using deep comparison on the inputs, not reference equality
TypeScript
1,726
star
9

mdx-bundler

🦀 Give me MDX/TSX strings and I'll give you back a component you can render. Supports imports!
JavaScript
1,702
star
10

react-performance

Let's make our apps fast ⚑
JavaScript
1,557
star
11

advanced-react-patterns-v2

Created with CodeSandbox
JavaScript
1,499
star
12

testing-workshop

A workshop for learning how to test JavaScript applications
JavaScript
1,363
star
13

babel-plugin-preval

🐣 Pre-evaluate code at build-time
TypeScript
1,357
star
14

advanced-react-patterns-v1

The course material for my advanced react patterns course on Egghead.io
HTML
1,092
star
15

react-testing-library-course

Test React Components with Jest and React Testing Library on TestingJavaScript.com
JavaScript
1,004
star
16

testing-react-apps

A workshop for testing react applications
JavaScript
977
star
17

kcd-scripts

CLI toolbox for common scripts for my projects
JavaScript
870
star
18

stop-runaway-react-effects

πŸƒ Catches situations when a react use(Layout)Effect runs repeatedly in rapid succession
JavaScript
788
star
19

netlify-shortener

Your own free URL shortener with Netlify
JavaScript
778
star
20

beginners-guide-to-react

The Beginner's Guide To ReactJS
HTML
757
star
21

react-suspense

React Suspense workshop
JavaScript
746
star
22

old-kentcdodds.com

Kent's Homepage
JavaScript
736
star
23

ng-stats

Little utility to show stats about your page's angular digest/watches.
JavaScript
657
star
24

dotfiles

Shell
510
star
25

js-testing-fundamentals

Fundamentals of Testing in JavaScript on TestingJavaScript.com
JavaScript
500
star
26

jest-cypress-react-babel-webpack

Configure Jest for Testing JavaScript Applications and Install, Configure, and Script Cypress for JavaScript Web Applications on TestingJavaScript.com
JavaScript
442
star
27

advanced-remix

TypeScript
393
star
28

react-testing-library-examples

Created with CodeSandbox
HTML
380
star
29

testing-node-apps

Test Node.js Backends on TestingJavaScript.com
JavaScript
365
star
30

es6-workshop

A very hands on πŸ‘ workshop πŸ’» about ES6 and beyond.
JavaScript
362
star
31

es6-todomvc

The vanillajs example converted to es6
JavaScript
353
star
32

babel-plugin-codegen

πŸ’₯ Generate code at build-time
TypeScript
347
star
33

eslint-config-kentcdodds

ESLint configuration for projects that I do... Feel free to use this!
JavaScript
338
star
34

cloc

An npm module for distributing cloc by Al Danial
JavaScript
325
star
35

asts-workshop

Improved productivity πŸ’― with the practical πŸ€“ use of the power πŸ’ͺ of Abstract Syntax Trees 🌳 to lint ⚠️ and transform πŸ”€ your code
JavaScript
295
star
36

how-jest-mocking-works

JavaScript
294
star
37

js-mocking-fundamentals

JavaScript Mocking Fundamentals on TestingJavaScript.com
JavaScript
281
star
38

webpack-config-utils

Utilities to help your webpack config be easier to read
JavaScript
262
star
39

express-app-example

How I structure Express Apps (example repo)
JavaScript
261
star
40

dom-testing-library-with-anything

Use DOM Testing Library to test any JS framework on TestingJavaScript.com
JavaScript
217
star
41

learn-react

Learn React with a laser focused, guided approach.
JavaScript
213
star
42

the-webs-next-transition

TypeScript
211
star
43

modern-react

workshop about React's hottest new features in 16.7.0
JavaScript
207
star
44

react-jest-workshop

JavaScript
199
star
45

react-github-profile

JavaScript
199
star
46

react-ava-workshop

🐯 A workshop repository for testing React βš› with AVA πŸš€ --> slides
JavaScript
192
star
47

api-check

VanillaJS version of ReactJS propTypes
JavaScript
191
star
48

starwars-names

Get a random Star Wars name
JavaScript
185
star
49

import-all.macro

A babel-macro that allows you to import all files that match a glob
JavaScript
177
star
50

remix-todomvc

An Implementation of TodoMVC with Remix
TypeScript
172
star
51

rtl-css-js

RTL for CSS in JS
JavaScript
162
star
52

react-workshop-app

An abstraction for all my React workshops
TypeScript
144
star
53

generator-kcd-oss

A yeoman generator for my open source modules
JavaScript
140
star
54

remix-workshop

TypeScript
133
star
55

issue-template

A way for github projects to make templates for github issues.
JavaScript
131
star
56

react-hooks-and-suspense-egghead-playlist

This is the code for the egghead playlist "React Hooks and Suspense"
JavaScript
128
star
57

modern-javascript

Get up to speed on the latest, most useful JavaScript features to level up your programming
JavaScript
123
star
58

kcd-discord-bot-v1

The bot for the KCD discord community
TypeScript
123
star
59

app-dev-tools

An example of how to create and hook up App DevTools to improve your development productivity of your application
JavaScript
122
star
60

preval.macro

Pre-evaluate code at build-time with babel-macros
JavaScript
120
star
61

split-guide

A tool to help generate code for workshop repositories
JavaScript
108
star
62

kcd-learning-clubs-ideas

πŸ“ Ideas for curriculum and schedule templates for KCD Learning Clubs
106
star
63

simply-react

JavaScript
104
star
64

nps-utils

Utilities for http://npm.im/nps (npm-package-scripts)
JavaScript
101
star
65

glamorous-website

This is still a work in progress
JavaScript
98
star
66

jest-glamor-react

Jest utilities for Glamor and React
JavaScript
98
star
67

react-hooks-pitfalls

The slides and code examples for my talk "React Hook Pitfalls"
JavaScript
94
star
68

webpack-validator-DEPRECATED

Use this to save yourself some time when working on a webpack configuration.
JavaScript
93
star
69

onewheel-blog

TypeScript
90
star
70

remix-tutorial-walkthrough

I live streamed working through the Remix Jokes App Tutorial
TypeScript
87
star
71

rebase-and-merge

Making this a reality ☞
JavaScript
82
star
72

managing-state-management-slides

79
star
73

css-in-js-precompiler

WORK IN PROGRESS: Precompiles CSS-in-JS objects to CSS strings
JavaScript
72
star
74

create-react-app-react-testing-library-example

JavaScript
67
star
75

10-practical-js-features

JavaScript
67
star
76

rename-gh-to-main

JavaScript
67
star
77

full-stack-components

TypeScript
66
star
78

fakebooks-remix

The Remix version of the fakebooks app demonstrated on https://remix.run. Check out the CRA version: https://github.com/kentcdodds/fakebooks-cra
TypeScript
66
star
79

cypress-testing-workshop

A workshop for learning how to write cypress tests
JavaScript
65
star
80

prettier-eslint-atom

DEPRECATED IN FAVOR OF prettier-atom + ESLint integration
JavaScript
64
star
81

repeat-todo

A simple app I made for my wife
JavaScript
63
star
82

why-react-hooks

Talk about React hooks
JavaScript
62
star
83

codegen.macro

JavaScript
61
star
84

talks

A repo with links to talks that I've given
59
star
85

quick-stack

TypeScript
57
star
86

binode

JavaScript
57
star
87

airtable-netlify-short-urls

There's a simpler version using Netlify redirects instead of Airtable here
JavaScript
57
star
88

fully-typed-web-apps-demo

TypeScript
53
star
89

argv-set-env

Set environment variables in npm scripts
JavaScript
52
star
90

react-test-context-provider

A function that allows you to specify context to pass to a child component (intended for testing only).
JavaScript
48
star
91

concurrent-react

React Suspense Egghead course
JavaScript
47
star
92

incremental-react-router-to-remix-upgrade-path

JavaScript
46
star
93

remix-mdx

JavaScript
45
star
94

setup-prettier

JavaScript
44
star
95

podcastify-dir

Take a directory of audio files and syndicate them with an rss feed
JavaScript
42
star
96

aha-programming-slides

JavaScript
42
star
97

workshop-setup

Verify and setup a repository for workshop attendees
JavaScript
42
star
98

jest-esmodules

JavaScript
40
star
99

typing-for-kids

A little app I made for my kids for Christmas :)
JavaScript
40
star
100

react-suspense-simple-example

JavaScript
39
star