React - Contexts
by Arnaud Buchholz
HTML
<div id="app"></div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
.done {
color: rgba(0, 0, 0, 0.3);
text-decoration: line-through;
}
input {
margin-right: 5px;
}
React
const UserContext = React.createContext({
loggedIn: false,
login: () => {}
});
class App extends React.Component {
constructor(props) {
super(props);
this.login = this.login.bind(this);
this.state = {
loggedIn: false,
login: this.login
};
}
login() {
this.setState({
loggedIn: !this.state.loggedIn
});
}
render() {
return (
<UserContext.Provider value={this.state}>
<Toolbar />
</UserContext.Provider>
);
}
}
function Toolbar(props) {
return (
<div>
<LoginButton />
</div>
);
}
class LoginButton extends React.Component {
login() {
this.context.login();
}
render() {
return (
<div>
<span>User is logged {this.context.loggedIn ? 'In' : 'Out'}</span><br />
<button onClick={this.context.login}>{this.context.loggedIn ? 'Logout' : 'Login'}</button>
</div>
);
}
}
LoginButton.contextType = UserContext;
ReactDOM.render(<App />, document.querySelector("#app"));