Skip to content

Instantly share code, notes, and snippets.

@trueadm trueadm/adopt-syntax.js
Last active Feb 23, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.