Skip to content

Instantly share code, notes, and snippets.

@nahumzs
Last active March 1, 2018 22:34
Show Gist options
  • Save nahumzs/fbea7bcf7ea2235323a09075a14caa33 to your computer and use it in GitHub Desktop.
Save nahumzs/fbea7bcf7ea2235323a09075a14caa33 to your computer and use it in GitHub Desktop.
export default class Form extends Component {
// Defining Context Types these are the properties that
// the consumer component can use.
static childContextTypes = {
onSent: func,
isDisabled: bool,
}
// Providing the actual values for the Context Types
// defined in childContextTypes
getChildContext() {
const { isDisabled } = this.props;
return {
isDisabled: this.state.isDisabled,
onSent: this.handleOnSent,
}
}
state = {
isDisabled: false,
}
handleOnSent = event => {
// having the callback in the parent component
// would allowed you theoretically update the state
// or process any business logic that you need.
event.preventDefault();
this.setState({ isDisabled: true });
return new Promise((resolve) => {
setTimeout(() => {
this.setState({ isDisabled: false });
resolve(true);
}, 3000);
});
}
render() {
return (
<form className="children-extend-form">
{this.props.children}
</form>
);
}
}
// Using context in a Class component
export class Button extends Component {
// Allowing the component to be aware of these
// context properties
static contextTypes = {
isDisabled: bool,
onSent: func,
}
// Accessing onSent function defined in the Form Component
// via this.context.onSent
handleOnClick = event => this.context
.onSent(event)
.then(response => {
alert('๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰๐ŸŒฎ๐ŸŒฎ๐ŸŒฎ๐ŸŒฎ');
});
render() {
return (
<button disabled={this.context.isDisabled} onClick={this.handleOnClick}>
Sent
</button>
);
}
}
// Statless component can received the context via the second argument
export const Input = (props, context) => {
return <input type="text" disabled={context.isDisabled} />
}
// Stateless component also can access the context
// properties as well adding contextTypes
Input.contextTypes = {
isDisabled: bool,
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment