Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Could isChecked prop be used as state of Switch button #6

Open
tahv0 opened this issue Nov 16, 2017 · 3 comments
Open

Could isChecked prop be used as state of Switch button #6

tahv0 opened this issue Nov 16, 2017 · 3 comments

Comments

@tahv0
Copy link

tahv0 commented Nov 16, 2017

Current implementation changes state of Switch Button in css styles.

This makes impossible to change its state programmatically. It could be nice if this Component could use isChecked-prop so its state would not change every time it's toggled.

My problem came up when I made "are u sure" confirm before making API call, and if user cancels then SwitchButton's state changes anyways because its state can not be controlled programmatically.

@willianjusten
Copy link
Contributor

Hum...it's true. At the moment I'm very busy with another stuff, do you want to create a PR?

@Sparragus
Copy link

@tahv0 or whoever ends up here... I faced this problem too in a project I just joined. I also needed a controlled version of this component. I considered doing a PR or forking this but since I was in a rush I decided to adapt it to my needs. Here's what I did:

import React, { Component } from “react”;
import PT from “prop-types”;
import SwitchButton from “lyef-switch-button”;

export default class ControlledSwitchButton extends Component {
  componentDidMount() {
    this.toggle = document.querySelector(`#${this.props.id}`);
  }

  componentDidUpdate(prevProps) {
    this.toggleSwitchIfNeeded(prevProps);
  }

  toggleSwitchIfNeeded(prevProps) {
    if (prevProps.isChecked !== this.props.isChecked) {
      this.toggleSwitch();
    }
  }

  toggleSwitch() {
    this.toggle.checked = this.props.isChecked;
  }

  render() {
    return <SwitchButton {...this.props} />;
  }
}

ControlledSwitchButton.propTypes = {
  id: PT.string.isRequired
};

Hope this helps future devs.

@StanleySathler
Copy link
Contributor

I created an initial Pull Request so we can have a base to discuss upon that. Any thoughts @willianjusten @tahv0?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants