<html>
<body>
<div id="root"></div>
</body>
</html>
.app {
height: 200px;
display: flex;
justify-content: space-around;
align-items: center;
flex-direction: column;
}
p {
margin: 0;
font-weight: bold;
font-size: 20px;
}
View Compiled
const { Component } = React;
class App extends Component {
render() {
return (
<StateManager>
<div className="app">
<p>Counter Demo</p>
<CounterDisplayContainer />
<CounterButtonContainer />
</div>
</StateManager>
);
}
}
const { Provider, Consumer } = React.createContext();
class StateManager extends Component {
static Consumer = Consumer;
state = { counter: 0 };
increment = () => {
this.setState(({ counter }) => ({ counter: counter + 1 }));
};
render() {
return (
<Provider
value={{
...this.state,
increment: this.increment
}}
>
{this.props.children}
</Provider>
);
}
}
const CounterDisplay = ({ counter }) => (
<div>{counter}</div>
);
const CounterDisplayContainer = (props) => (
<StateManager.Consumer>
{({ counter }) => (
<CounterDisplay counter={counter} {...props} />
)}
</StateManager.Consumer>
);
const CounterButton = ({ onClick }) => (
<button onClick={onClick}>Increment</button>
);
const CounterButtonContainer = (props) => (
<StateManager.Consumer>
{({ increment }) => (
<CounterButton onClick={() => increment()} {...props} />
)}
</StateManager.Consumer>
);
ReactDOM.render(
(<App />),
document.getElementById('root')
);
View Compiled
This Pen doesn't use any external CSS resources.