Skip to content

Instantly share code, notes, and snippets.

@nullhook
Last active July 20, 2022 08:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nullhook/0203b2f9b7395f2aaafb9e8f39a2d20d to your computer and use it in GitHub Desktop.
Save nullhook/0203b2f9b7395f2aaafb9e8f39a2d20d to your computer and use it in GitHub Desktop.
Advance React Patterns
// A component with accessors
// The accessors can only be accessed inside the actual component
function C(props) {
// ...
}
C.bar = () => {
// this method can be accessed within the component
}
C.div = ({ children }) => {
// ...
}
function App() {
return (
<React.Fragment>
<Component foo="bar">
{C.bar()}
<C.div>
<p>Foo</p>
</C.div>
</Component>
</React.Fragment>
)
}
// Hooks that return an object
function useC() {
return {
foo: () => {},
bar: undefined,
div: ({ children }) => <div>{children}</div>
}
}
function App() {
const C = useC():
return (
<React.Fragment>
{C.foo()}
{C.bar}
<C.div>
<p>Foo</p>
</C.div>
</React.Fragment>
);
}
// A component with acessors
// Accessors that can return react element
// Accessors that can return ES6 class object
function Empty() { return null; }
class E { constructor(a,b) { this.a = a; this.b = b; }}
function C({ childen }) {
// Children here returns a JSX object
// It can also return a class object with `new`
// You can also use React.Children.map to ensure children is not always an array
const items = children.map(child => {
if (child instanceof E) { // ... }
if (child && child.type === Empty) { // ... }
});
return React.createElement(React.Fragment, {}, ...items);
}
C.foo = (noop) => {
return <Empty foo={noop} />
}
C.bar = (a, b) => {
return new E(a, b);
}
function App() {
return (
<React.Fragment>
<C>
<p>Foo</p>
{C.foo(() => {})}
{C.bar(2,3)}
</C>
</React.Fragment>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment