Last active
February 20, 2019 17:38
-
-
Save reeddunkle/26e7f8192a6ab2eda29fcfd82364a0df to your computer and use it in GitHub Desktop.
Atlaskit's Controlled Component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Example copied from: https://atlaskit.atlassian.com/packages/core/datetime-picker | |
Usage: | |
<Controlled initialValue="2018-01-02"> | |
{({ value, onValueChange, onBlur }) => ( | |
<DatePicker | |
id="datepicker-2" | |
value={value} | |
onChange={onValueChange} | |
onBlur={onBlur} | |
/> | |
)} | |
</Controlled> | |
*/ | |
class Controlled extends Component<Props, State> { | |
state: State; | |
recentlySelected: boolean = false; | |
constructor(props: Props) { | |
super(props); | |
this.state = { | |
value: props.initialValue || '', | |
isOpen: props.initialIsOpen || false, | |
}; | |
} | |
handleClick = () => { | |
if (!this.recentlySelected) { | |
this.setState({ isOpen: true }); | |
} | |
}; | |
onValueChange = (value: string) => { | |
console.log(value); | |
this.recentlySelected = true; | |
this.setState( | |
{ | |
value, | |
isOpen: false, | |
}, | |
() => { | |
setTimeout(() => { | |
this.recentlySelected = false; | |
}, 200); | |
}, | |
); | |
}; | |
onBlur = () => { | |
this.setState({ | |
isOpen: false, | |
}); | |
}; | |
onFocus = () => { | |
this.setState({ | |
isOpen: false, | |
}); | |
}; | |
render() { | |
return ( | |
// eslint-disable-next-line jsx-a11y/no-static-element-interactions | |
<div onClick={this.handleClick}> | |
{this.props.children({ | |
value: this.state.value, | |
onValueChange: this.onValueChange, | |
isOpen: this.state.isOpen, | |
onBlur: this.onBlur, | |
})} | |
</div> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment