Advance React Patterns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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> | |
) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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> | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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