Skip to content

Instantly share code, notes, and snippets.

View alexandrzavalii's full-sized avatar
🏠
Working from home

alex alexandrzavalii

🏠
Working from home
View GitHub Profile
// JSX
const Dumbo = props => {
return <div>Hey, my name is Dumbo.</div>;
};
// without JSX
const Dumbo = props => {
return React.createElement("div", null, `Hey, my name is Dumbo.`);
};
class Dumbo extends React.Component {
// static getDerivedStateFromProps(nextProps, prevState){ return prevState; }
state = { clothing : 'hat' };
// componentDidMount() { }
// shouldComponentUpdate() { }
// getSnapshotBeforeUpdate() { }
// componentWillUnmount() { }
class Dumbo extends React.Component {
state = { clothing: null, firstChild: null, secondChild: null };
handleState = () => {
this.setState({
clothing: "jeans",
firstChild: "shoes",
secondChild: "hat"
});
};
render() {
class DumbosParent extends React.Component {
state = { availableShoes: 6 };
sellShoes = () => {
this.setState(({ availableShoes }, props) => ({
availableShoes: availableShoes > 1 && availableShoes - 1
}));
};
render() {
class DumbosParent extends React.Component {
state = { availableShoes: 6, lollipops: 2 };
/* sellShoes */
render() {
const { availableShoes, lollipops } = this.state;
return (
<>
/* rest of code */
<Dumbo availableShoes={availableShoes} lollipops={lollipops} />
</>
/* parent component */
const { lollipops } = this.state;
return (
<div>
<Dumbo availableShoes={availableShoes} candys={lollipops} />
</div>
);
/* Dumbo component */
const { candys } = this.props;
/* Dumbo's parent component */
const { lollipops } = this.state;
return (
<div>
<Dumbo availableShoes={availableShoes} lollipops={lollipops} />
</div>
);
/* Dumbo component */
render () {
/* HOC for wrapping the component with Context Provider */
const connect = Component => {
return function WrappedComponent(props) {
return (
<CandyContext.Consumer> /* pass lollipops as a prop */
{value => <Component {...props} lollipops={value} />}
</CandyContext.Consumer>
);
};
};
// create Context
const initialAmountOfLollipops = 0;
const LollipopContext = React.createContext(initialAmountOfLollipops);
/* ... Dumbo's parent Component */
const { lollipops } = this.state;
return (
// instead of passing lollipops to Dumbo, we pass it to the Context.Provider
<CandyContext.Provider value={lollipops}>
<Dumbo availableShoes={availableShoes} /* lollipops={lollipops} */ />
import React from "react";
import FirstChild from "./FirstChild";
import SecondChild from "./SecondChild";
class DumbosParent extends React.Component {
state = { availableShoes: 6, lollipops: 9 };
render() {
const { availableShoes, lollipops } = this.state;
return (