Skip to content

Instantly share code, notes, and snippets.

@trueadm
Last active November 27, 2021 03:32
Show Gist options
  • Star 30 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save trueadm/17beb64288e30192f3aa29cad0218067 to your computer and use it in GitHub Desktop.
Save trueadm/17beb64288e30192f3aa29cad0218067 to your computer and use it in GitHub Desktop.
Adding a the "adopt" keyword to the JSX syntax
// I'm suggesting we add a new "adopt X from <Y />" syntax to the JSX language
// it would de-sugar to render prop children, but look and read better than
// what we currently have. For example:
// 1.
// this sugar
function MyComponent(props) {
adopt foo from <Bar />;
return <div>{foo}</div>;
}
// compiles to
function MyComponent(props) {
return <Bar>{foo => <div>{foo}</div>}</Bar>
}
// 2.
// with the new context API without sugar
const ThemeContext = React.createContext('light');
class Title extends React.Component {
render() {
return (
<ThemeContext.Consumer>
{theme => (
<h1 style={{color: theme === 'light' ? '#000' : '#fff'}}>
{this.props.children}
</h1>
)}
</ThemeContext.Consumer>
);
}
}
// with "adopt" sugar
const ThemeContext = React.createContext('light');
class Title extends React.Component {
render() {
adopt theme from <ThemeContext.Consumer />;
return (
<h1 style={{color: theme === 'light' ? '#000' : '#fff'}}>
{this.props.children}
</h1>
);
}
}
// 3.
// how we might handle state without classes
const State = React.createState({
title: "",
});
class Title extends React.Component {
render() {
adopt { state } from <State
initialState={() => ({
return { title: this.props.title || "Hello world" };
})}
deriveStateFromProps={state => {
// ...
}}
shouldUpdate={state => {
// ...
}}
didMount={state => {
// ...
}}
didUpdate={state => {
// ...
}}
willUnmount={state => {
// ...
}}
/>;
return <div>{state.title}</div>
}
}
// 4.
// how we might handle state without classes and need refs
const State = React.createState({
divRef: null,
});
class Title extends React.Component {
render() {
adopt { state } from <State
initialState={() => ({
divRef: React.createRef(),
})}
didMount={state => {
state.divRef.value.focus();
}}
/>;
return <input type="text" ref={state.divRef} />
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment