Coder Social home page Coder Social logo

kentcdodds / react-toggled Goto Github PK

View Code? Open in Web Editor NEW
453.0 12.0 39.0 314 KB

Component to build simple, flexible, and accessible toggle components

Home Page: https://codesandbox.io/s/m38674w9vy

License: MIT License

JavaScript 94.43% TypeScript 5.57%

react-toggled's Introduction

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

react-toggled's People

Contributors

allcontributors[bot] avatar andarist avatar andrewmcodes avatar ashiknesin avatar bslinger avatar jaredpalmer avatar jdorfman avatar josephlin55555 avatar oliverjam avatar palashmon avatar tansongyang avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-toggled's Issues

Should onToggle get called when receiving new on prop in controlled mode?

Im wondering if this is a correct behaviour - if we take DOM element such as input as an example the onChange wont be called in this case.

I realize that this might be purely because onChange is assiociated with DOM event which is not fired in that case, but maybe this (and other similar components) shouldnt fire their onChangedValue~ handlers in case of "programmatic change". WDYT?

This is more of a general question rather than about this lib, but answer for that question affects expected behaviour of this one, so I thought it's a good place to discuss this.

The funny thing is that I have requested adding this 😂 and even I've implemented firing. After the time - it seems that it was a bad decision to make and it seems that downshift doesnt fire handlers for that case.

Discussion: Should props also include tabIndex and onKeyDown?

First of all, thanks for making this. I really like the direction that this project and downshift are taking.

I tried my hand at making a little switch component. You'll see that I call getTogglerProps on an <input>. I then hide it under the control that I want to be displayed. I do this because it lets me tab to the control and toggle with the spacebar.

I originally wanted to be able to do something like this. This does not use a hidden <input>. It still works with clicking, but you can't tab to it.

My question: Do you think it is within the scope of this project to get tabbing for free?

I've glanced at getTogglerProps. I think you could achieve this by adding the following props.

{
  tabIndex: props.tabIndex == null ? 0 : props.tabIndex, // In case users wanted a specific value
  onKeyDown: callAll(props.onKeyDown, this.toggleIfCorrectKey), // I'm open to a better name
}

If I'm not mistaken, this should keep existing functionality for inputs, buttons, etc., while allowing raw <span>s and other elements to gain new functionality.

aria-controls='target'

  • react-toggled version: 1.1.2
  • node version: 8.9.0
  • npm (or yarn) version: 5.5.1

This is more of a question than a bug, so apologies if I've missed something obvious.

You set the aria-controls attribute to 'target' in getTogglerProps, but I can't see this being set as an ID anywhere. Is 'target' a special value that aria-controls can take or is the ID just missing from the target element?

Thanks for this library by the way—it's a great intro to render props 👍

README appears to be broken

The README appears to be broken:

tmp

As you can see, the react-toggled link seems malformed. I would have changed this myself, but the comments say not to edit that section because it is auto-generated.

[Question] Why you used the getOn function instead of React defaultProps?

  • react-toggled version: 1.2.2
  • node version: --
  • npm (or yarn) version: --

Relevant code or config

What you did:

What happened:

Reproduction repository:

Problem description:
Hello,
I'm reading your source code. I can't figure out that why you used the getOn function instead of React defaultProps?
Please see this my stackblitz Link. What difference between code that you wrote and it's my own code?
Thanks.
Suggested solution:

Update tweet to include username

Problem description & Suggested Solution:

I was looking at the readme and found that the tweet text you have currently is like:

Check out react-toggled! https://github.com/kentcdodds/react-toggled 👍

I think it can be updated to include your user name like:

Check out react-toggled by @kentcdodds https://github.com/kentcdodds/react-toggled 👍

This will help you to directly get notified whenever someone post a new tweet and thereafter you can respond to them instantly. Currently you can only do this by twitter search manually.

I will create a PR for this in a moment.

Regards!

Multiple toggle variables

Hi @kentcdodds,

Thanks for a great component. I really like these utility component that only implement the logic part like react-toggled and downshift.

As for this component, I'm wondering if you have thought about making a MultiToggle of some sort. It'd do everything the Toggle is doing, but with more control props (on_1, on_2, etc). Is it something you thought about but decide not to do? Is it an anti-pattern of some sort?

I'm thinking of making something like that and came across this component. I'd be happy to implement it if you think it'd be useful.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.