Skip to content

Instantly share code, notes, and snippets.

@IPRIT
Created February 26, 2020 17:55
Show Gist options
  • Select an option

  • Save IPRIT/cc5c90bc7b862f6f99d27f519d033a96 to your computer and use it in GitHub Desktop.

Select an option

Save IPRIT/cc5c90bc7b862f6f99d27f519d033a96 to your computer and use it in GitHub Desktop.
import React, { useEffect, useContext } from "react";
import "./styles.css";
const isNode = true;
const baobab = isNode ? { name: "page", children: [] } : null;
const Ctx = React.createContext(baobab);
function useBaobab(name, attrs) {
const id = Math.random();
const parent = useContext(Ctx);
let node = null;
if (isNode) {
node = { name, id };
if (attrs) {
node.attrs = attrs;
}
if (!parent.children) {
parent.children = [];
}
parent.children.push(node);
}
const Provider = props => (
<Ctx.Provider value={node}>{props.children}</Ctx.Provider>
);
return [id, Provider];
}
function Main(props) {
const [id, Provider] = useBaobab("main");
return (
<Provider>
<div data-id={id}>{props.children}</div>
</Provider>
);
}
function Card() {
const [id, Provider] = useBaobab("card", { cl4url: Math.random() });
return (
<Provider>
<div data-id={id}>CARD{id}</div>
</Provider>
);
}
export default function App() {
const [id, Provider] = useBaobab("app");
useEffect(() => {
console.log(baobab);
}, []);
return (
<Provider>
<div className="App" data-id={id}>
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<Main>
<Card />
<Card />
<Card />
</Main>
</div>
</Provider>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment