const { Provider, Consumer } = React.createContext(defaultValue);
import { createContext } from 'react';
export default createContext(() => {});
import React, { Component } from 'react';
import AdvertisingContext from './AdvertisingContext';
import Advertising from './Advertising';
export default class extends Component {
constructor(props) {
super(props);
this.advertising = new Advertising(props.config);
}
render() {
return (
<AdvertisingContext.Provider value={this.advertising.activate}>
{this.props.children}
</AdvertisingContext.Provider>
);
}
}
import React, { Component } from 'react';
import AdvertisingContext from './AdvertisingContext';
class AdvertisingSlot extends Component {
componentDidMount() {
const { activate, id } = this.props;
activate(id);
}
render() {
return <div id={this.props.id} />
}
}
export default props => (
<AdvertisingContext.Consumer>
{activate => <AdvertisingSlot {...props} activate={activate} />}
</AdvertisingContext.Consumer>
);
// Old context API
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class MyProvider extends Component {
getChildContext() {
return { message: 'hello world' };
}
render() {
return this.props.children;
}
}
MyProvider.childContextTypes = {
message: PropTypes.string
};
class MyConsumer extends Component {
render() {
return <h1>{this.context.message}</h1>
}
}
MyConsumer.contextTypes = {
message: PropTypes.string
};
export default () => (
<MyProvider>
<MyConsumer />
</MyProvider>
);
// New context API
import React, {
Component,
createContext
} from 'react';
const { Provider, Consumer } = createContext();
function MyProvider({ children }) {
return (
<Provider value="hello world">
{children}
</Provider>
);
}
function MyConsumer(props) {
return (
<Consumer>
{message => <h1>{message}</h1>}
</Consumer>
);
}
export default () => (
<MyProvider>
<MyConsumer />
</MyProvider>
);
Other usecase examples
besides getting rich quick:
Follow me on Twitter:
@wiekatz
Patrick Hund, frontend developer at eBay Tech Berlin
View the slides:
technology-ebay-de.github.io/get-rich-quick-with-react-context/
View the code examples:
codesandbox.io/s/488y5n5kw
codesandbox.io/s/3rz877y8jm