Giter Site home page Giter Site logo

aaronshaf / react-toggle Goto Github PK

View Code? Open in Web Editor NEW
945.0 15.0 159.0 3.44 MB

Elegant, accessible toggle component for React. Also a glorified checkbox.

Home Page: http://aaronshaf.github.io/react-toggle/

License: MIT License

JavaScript 86.38% CSS 10.69% HTML 2.93%
react toggle

react-toggle's Introduction

An elegant, accessible toggle component for React. Also a glorified checkbox.

See usage and examples.

Props

The component takes the following props.

Prop Type Description
checked boolean If true, the toggle is checked. If false, the toggle is unchecked. Use this if you want to treat the toggle as a controlled component
defaultChecked boolean If true on initial render, the toggle is checked. If false on initial render, the toggle is unchecked. Use this if you want to treat the toggle as an uncontrolled component
onChange function Callback function to invoke when the user clicks on the toggle. The function signature should be the following: function(e) { }. To get the current checked status from the event, use e.target.checked.
onFocus function Callback function to invoke when field has focus. The function signature should be the following: function(e) { }
onBlur function Callback function to invoke when field loses focus. The function signature should be the following: function(e) { }
name string The value of the name attribute of the wrapped <input> element
value string The value of the value attribute of the wrapped <input> element
id string The value of the id attribute of the wrapped <input> element
icons object If false, no icons are displayed. You may also pass custom icon components in icons={{checked: <CheckedIcon />, unchecked: <UncheckedIcon />}}
aria-labelledby string The value of the aria-labelledby attribute of the wrapped <input> element
aria-label string The value of the aria-label attribute of the wrapped <input> element
disabled boolean If true, the toggle is disabled. If false, the toggle is enabled

Installation

npm install react-toggle

Usage

If you want the default styling, include the component's CSS with

import "react-toggle/style.css" // for ES6 modules
// or
require("react-toggle/style.css") // for CommonJS

Development

npm install
npm run dev

Build

npm run build

License

MIT

react-toggle's People

Contributors

aaronshaf avatar adam187 avatar ahstro avatar bdiehr avatar bnadeau avatar brentropy avatar bripkens avatar bryceallison avatar codelpham avatar cvpcasada avatar ihenshaw avatar jedwards1211 avatar jnsdls avatar jolyonruss avatar kelly-tock avatar kyleamathews avatar lex111 avatar lfbn avatar mbseid avatar nathanstitt avatar nrempel avatar pgilad avatar rassell avatar ribeiroct avatar robmunro avatar rodrix avatar rovolution avatar th3fallen avatar tremby avatar ungerik 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  avatar  avatar  avatar

react-toggle's Issues

Swipe improvements

Exciting opportunities to improve this using paper-toggle as an example.

  • Support swipe with mouse
  • Move knob along with X coordinate of pointer/cursor (right now it waits until new checked value is inferred)
  • Trigger checked/unchecked visual state upon cross middle x coordinate of toggle
  • Show bigger active visual state for touch events (visual state bigger than the finger)

Version control of bundles/dist

Should the compiled bundles really be version controlled? AFAIK, this makes for a messy git history as well as inaccurate diffs (I have 20k+ additions already 😰 ).

I'm not sure how this works with npm, it was a long time since I published there. Also, not tracking them would prevent people from using the repo directly in their package.json-files.

Maybe we should just commit the compiled files when we're releasing a new veresion? Or maybe there's a way to not track it at all but include it in releases/on npm somehow?

Change file structure

As it is now, the structure of this project feels a bit chaotic, with almost everything living in the root.
I would like to move things into subdirectoris, so that we have a file structure that looks more like this:

src/
  x.js
  check.js
  index.js
  index.html
  style.css
dist/
  bundle.js
  index.html
  style.css
docs/
  index.html
  style.css
LICENSE
README.md
package.json
webpack.config.js
.gitignore
.npmignore

Now, I'm not particularly familiar with all files in the project yet, but you (hopefully) get the gist of it :)
Basically, we would have everything that will be compiled into the module in src, the compiled bundle in build (this is what npm and docs will use), docs will contain what is now split between the examples subdirectory and the gh-pages branch - i.e., the documentation where people can see the module in action and what people can use to test it out when developing.

If this sounds okay, I can get on it (after merging some PRs so they don't have to rebase), otherwise, just close this. @aaronshaf

Meteor compatibility

Hi,

would you know how to integrate your pacakge with Meteor? I tried this:

render() {
        var Toggle = Npm.require('react-toggle');

        return (
            <div className="container">
                <header>
                    <div className="header-center">LOGO</div>
                </header>

                <Toggle
                    defaultChecked="true" />

            </div>
        );

and this is breaking my other components. I did the npm install step.

Thanks for your help!

use of PureComponent requires updated peerDependency for react >= 15.3.0

I just got bit when npm install installed react-toggle v2.2.1 but we're still using react v15.0 which is incompatible due to use of PureComponent. It looks like PureComponent was added in react v15.3. So this package's peerDependency needs to read "react": "^15.3.0"

Also it seems v2.2.1 is published on npm but it is not tagged on github or changelog updated.

Controlled component without onChange is not controlled at first click

Hi,

On the demo page : http://aaronshaf.github.io/react-toggle/
In the section : " Controlled Component without onChange"
If you click on the checkbox, the component is actually controlled and it works great, but if you click on the component itself, it's been checked for the first time, and after it you can't toggle it another time, it's the expected behavior.

Why the toggle is actually toggled just for the first time ?

Thanks

Double rendering -- this.state.checked is wrong

Helloes,
I've noticed a strange behavior in render function of index.js

I'm initiating my toggle with simple setup:
<Toggle onChange={ this.handleChange.bind(this) } checked={ this.state.launchOnMatchStart } />

handleChange sets my own component's state and writes to localStorage, then while initiating the Toggle again for the second time, I read the localStorage value if it exists.

In index.js, when I place my console.logs like this:

key: 'render',
    value: function render() {
      var _this2 = this;

      var _props = this.props;
      var className = _props.className;
      var _icons = _props.icons;
      console.log("node4: " + this.state.checked);
      var inputProps = _objectWithoutProperties(_props, ['className', 'icons']);
      var classes = (0, _classnames2.default)('react-toggle', {
        'react-toggle--checked': this.state.checked,
        'react-toggle--focus': this.state.hasFocus,
        'react-toggle--disabled': this.props.disabled
      }, className);
      console.log("node5: " + JSON.stringify(classes))

I get the following output:

app-3838027….js:2789 storage: false
app-3838027….js:2790 init: false
app-3838027….js:2824 render: false
vendor-3838027….js:9047 node3: false
vendor-3838027….js:9158 node4: false
vendor-3838027….js:9165 node5: "react-toggle"
app-3838027….js:2824 render: false
vendor-3838027….js:9158 node4: true
vendor-3838027….js:9165 node5: "react-toggle react-toggle--checked"

Notice the node4 and node5 repeating at the end.
node4 and node5 are from index.js - render, which gets triggered twice on init. And on the second trigger, this.state.checked changes value (from false to true), so my Toggle component is rendered as true although all my other variables log as false.

I also changed

_this.state = {
      checked: !(props.checked || props.defaultChecked),
      hasFocus: false
    };

in index.js - function Toggle() because although props.checked was correct, this.state.checked was always the opposite. With a single exclamation mark down, it's now correct; but the issue stands since it triggers render() twice.

render function is not pure

The render function calls isChecked, which has:

if (this.refs.input) {
    return this.refs.input.getDOMNode().checked
}

React then warns:

"Warning: PublishToggle is accessing getDOMNode or findDOMNode inside its render(). render() should be a pure function of props and state. It should never access something that requires stale data from the previous render, such as refs. Move this logic to componentDidMount and componentDidUpdate instead."

Unknown DOM property fill-rule

Version

  • react-toggle 2.1.0
  • React 15.1.0.

Problem

When I use react-toggle, I get an error:

Warning: Unknown DOM property fill-rule. Did you mean fillRule

I don't get the error when I remove react-toggle from my component.

Needs the option to be used as a "Controlled Component"

As of right now react toggle only works as an Uncontrolled Component. This works fine in some cases, but once mounted there is no way for something external to change the state of the toggle. There needs to be the option of using at as Controlled Component (i.e. use the checked prop instead of the internal checked state.) If I have time I will do a pull request.

console.warn when no label is provided

After mounting, we could check for either an inline label / labelledby or the ancestor nodes to ensure there is a wrapper. If not, we can throw an accessibility warning.

Keep a changelog

I'm thinking we should keep a changelog, mostly because I love reading them myself, but also to, you know, give the users information on what happened when and if things are being removed or changed. ;)

I'm currently writing one, but there were two things I wanted to discuss about it:

  1. Semantic versioning

    I feel like this is a great way to do versioning, and if you agree, we should stick to it from now on. This comment alluded to the fact that this project hasn't in the past, whether accidentally or not, but I propose we mention in the log that we follow SemVer as of version 2.1.0?

  2. Attribution

    Should there be any type of attribution in the changelog? If so, how should we go about it? There are a few alternatives, but the two that feels most appropriate is to either link the relevant commit next to the change, or link to the commiters GitHub profile via @. Honestly, I don't know if I feel like attribution belongs in a changelog though; the only reason I bring it up is that it was present in Keep a Changelog's own log.

toggle is reverted to old state after swipe

Step to reproduce this error:

  • click to check
  • swipe to uncheck
  • now the toggle is reverted to checked.

I set some breakpoints and discover that this.previouslyChecked has wrong value in function handleTouchEnd

New release

Would be great if you could release the latest changes to make sure that react-toggle is compatible with React 16. Thanks!

Cannot read property 'focus' of undefined

Hi just implementing react-toggle, with ES6 - import Toggle from 'react-toggle' and getting a error
-- Cannot read property 'focus' of undefined -- appears for checkbox.focus() so looks like it can't find this.refs.input

Wondering what I am doing wrong. I basically just added on the view without passing anything.

Updated version to 2.2.1 breaks my app?

index.js:37Uncaught TypeError: Super expression must either be null or a function, not undefined(…)

I guess its got something PureComponent change recently.

Feature request: optional additional class(es) on component

It would be nice if Toggle took a prop of additional classNames to add to the base component. This would support things like e.g. making different color toggles (.react-toggle.blue) or different sizes (.react-toggle.big). So my toggle would look like

 <Toggle classNames={'blue big'} ... />

In order to accomplish the same thing now I'd have to create a wrapper with the classes and my styles would have to all use !important to override the existing definitions.

Cannot resolve module 'react-addons-shallow-compare'

Can anyone please tell if there is any dependency issue with the current version?

I am getting following errors on using latest versions


Module not found: Error: Cannot resolve module 'react-addons-shallow-compare' in /Users/aragorn/wealthy/taxo_new/node_modules/react-toggle/dist/component
 @ ./~/react-toggle/dist/component/index.js 29:33-72

This works fine with version 2.1.1.

Can someone please help me on this?

CommonJS import error

Hello,

I followed the guide and attempted to use the CommonJS import:
const Toggle = require('react-toggle')

And got these 2 errors:

Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: object.

Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of StatelessComponent.

Which could be resolved by changing the import:
const Toggle = require('react-toggle').default
or adding
module.exports = Toggle;

to index.js.

Add linting

I noticed there were some discrepancies in the syntax being used, so I propose we add linting into the development mix, what do you think @aaronshaf?

I nominate my favorite combo: ESLint plus standardjs's sharable config. We're already not using semicolons for the most part, so we've already passed the biggest hurdle people see with standardjs. 😇

Allow a onClick prop so we can stop propagation

I have a use case where the Toggle button is on a list of items which are selectable by a mouse click.
So switching the toggle state also propagates a click event and my list item selection gets toggled too and I don't want that :)

All we need to prevent this is to be able to pass an onClick handler as a prop to the Toggle component so we can just do a event.stopPropagation and thus prevent further event handlers to be executed (in my case the container's click event which toggles the item selected state).

For now I need to check the target manually in the parent's click handler.

Cheers

Use CSS preprocessor

Query/Feature Request.

+ This can be really handy for consolidating meaning into seemingly magic hex.
+ Great way of allowing extensions.
- Complicates the stack with yet another dependency
- No standard pre-processor; do you use scss, sass, stylus etc…

If this is of any interest to the direction of the project I could look at opening a PR. Alternatively, completely understandable if you'd rather take the KISS approach.

FastClick breaks react-toggle

So I just started testing my app with toggles on an iPad using FastClick to get rid of the 300ms click delay. It turns out FastClick somehow breaks react-toggle (it wouldn't toggle when tapped), and I assume it's because of the call to checkbox.click(). I disabled FastClick on the toggles by giving them (and subcomponents) the needsclick class, but then, of course, they suffer from the 300ms click delay as before.

Given this, one can imagine the toggle might not work correct on other strange devices/environments.

Once realizing that the problem would be solved if I removed the checkbox altogether, I got to thinking, is the hidden checkbox really that necessary? I suppose it's nice to get the same event in an onChange handler as you'd get from a checkbox, so that you can just use toggles as a drop-in replacement for checkboxes. But even so, if we got rid of the checkbox we could still program the toggle to pass a fake event object with at least a value property to the onChange handler.

Eliminate the outline

Version

  • react-toggle 2.1.0
  • React 15.1.0.
  • Chrome 51.0.2704.103

When I interact with react-toggle, the circle has an outline and it's weird from the user's point of view.

react-toggle

I tried to put outline: none in DOM elements rendrered by react-toggle, but could not make it disappear. It shows when .react-toggle is :active. Any ideas on how to hide it? Happy to do a PR.

Improve test coverage

I've setup testing and added a few tests, but we still need to improve the coverage a lot.

I ran into some trouble when trying to test the actual click/toggle functionality (which is a pretty big part of the component). Using Enzyme's .simulate('click') doesn't seem to propagate properly; this is a known issue with their shallow rendering, but it also doesn't seem to work with full DOM rendering.

If anyone wants to give this a shot, that'd be great, just let me know and I'll assign you; otherwise, I'm going to try to get to this when I have time. :)

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.