Skip to content

Commit

Permalink
Change on property logic for Switch
Browse files Browse the repository at this point in the history
  • Loading branch information
elainen committed Oct 8, 2018
1 parent abaf8ca commit 621a090
Showing 1 changed file with 18 additions and 5 deletions.
23 changes: 18 additions & 5 deletions packages/simple-actions/hz-switch/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,34 +12,47 @@ type RenderProps = {

type Props = {
render: (props: RenderProps) => Element<*>,
defaultOn: boolean,
/**
* Provide optional default value
*/
isOn?: boolean,
on: boolean,

onSwitch?: (value: boolean) => void,
};

type State = {
isOn: boolean,
on: boolean,
};

class Switch extends Component<Props, State> {
static defaultProps = {
defaultOn: false,
};

state = {
isOn: this.props.isOn || false,
on: this.getOn({on: this.props.defaultOn}),
};

componentDidUpdate(_: any, prevState: State) {
if (
typeof this.props.onSwitch === 'function' &&
prevState.isOn !== this.state.isOn
prevState.on !== this.state.on
) {
this.props.onSwitch(this.state.isOn);
this.props.onSwitch(this.state.on);
}
}

handleToggleSwitch = () => {
this.setState((state: State): ?State => ({...state, isOn: !state.isOn}));
getOn(state: State = this.state): boolean {
return this.isOnControlled() ? this.props.on : state.on;
}

isOnControlled(): boolean {
return this.props.on !== undefined;
}

};

render() {
Expand Down

0 comments on commit 621a090

Please sign in to comment.