lennythedev

React context cardio 🏃‍

October 10, 2019

import React from "react";

const ThemeContext = React.createContext();

/*
v1 - using props.children

const Grandparent = (props) => <div>{props.children}</div>;

const Parent = (props) => <div>{props.children}</div>;

const Child = (props) => <div>{props.name}</div>;

				<Grandparent>
					<Parent>
						{({ name }) => (<Child name={name} />)}
					</Parent>
				</Grandparent>

v2 - using Prop Drilling

const Grandparent = (props) => <Parent {...props} />;

const Parent = (props) => <Child {...props} />;

const Child = (props) => <div>{props.name}</div>;

		return (
			<div>
				< Grandparent name={this.state.name} />
			</div>
		)

*/

const Grandparent = (props) => <Parent {...props} />;

const Parent = (props) => <Child {...props} />;

// using context consumer
const Child = () => (
	<ThemeContext.Consumer>
		{({ name }) => (<div>{name}</div>)}
	</ThemeContext.Consumer>
)

class Context extends React.Component {

	state = {
		name: "Lenny"
	};

	render() {
		return (
			<div>
				<ThemeContext.Provider value={this.state}>
					<Grandparent />
				</ThemeContext.Provider>
			</div>
		)
	}

}

export default Context;

lenmorld
Full-stack ramblings and journal about anything web