Skip to content

Commit

Permalink
feat: add <Prompt> component
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Jan 24, 2018
1 parent 9c13733 commit e281b0e
Showing 1 changed file with 52 additions and 0 deletions.
52 changes: 52 additions & 0 deletions src/Prompt/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import {PureComponent} from 'react';
import {noop, isClient} from '../util';

export interface IPromptProps {
children?: React.ReactElement<any> | ((result: string) => React.ReactElement<any>);
show?: boolean;
message?: string;
default?: string;
onResult?: (result: string) => void;
}

export class Prompt extends PureComponent<IPromptProps, any> {
componentDidMount () {
if (!(typeof this.props.children === 'function')) {
this.prompt();
}
}

componentDidUpdate () {
if (!(typeof this.props.children === 'function')) {
this.prompt();
}
}

prompt (): string {
const {show, message, default: def, onResult} = this.props;

if (show) {
const result = prompt(message, def);

(onResult || noop)(result);

return result;
}
}

render () {
const {children, default: def} = this.props;

if (typeof children === 'function') {
if (isClient) {
const result = this.prompt();

return children(result);
} else {
return children(def);
}
} else {
return (children as React.ReactElement<any>) || null;
}
}
}

0 comments on commit e281b0e

Please sign in to comment.