DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Jim Montgomery
Jim Montgomery

Posted on

the web platform: lighten the JSX load in React apps

We can simplify, modernize and accelerate UI work with React by translating templates at runtime as-is. Several years ago browsers implemented a new way of embedding expressions in strings called template literals (backticks with ${ expressions }), including tagging these expressions for specific handling. We can modernize our React apps by moving the template work in JSX build processes to the runtime using these template literals and the HTM helper library. This removes the associated transformation cost in development, simplifying build processes while also mostly removing the need to maintain knowledge related to the differences between standard HTML and this XML dialect. The HTM library itself offers a list of additional conveniences over JSX that I've come to expect in conventional work like supporting self-closing tags, better fragment handling, etc. Here's a simplified example and linked working gist and demo:

const jsx = htm.bind(React.createElement);

class App extends React.Component{
    constructor(props){
        super(props);
        const count = Number(props.count) || 0;
        this.state = { count };
        this.update = this.update.bind(this);
    }
    update(e){
        let {count} = this.state;
        count++;
        this.setState({count});
    }
    render(){
        return jsx`
<label>
click ${ this.state.count }  <button onClick=${ this.update }> from ${ this.props.count } </button>
</label>
        `;
    }
}

ReactDOM.render(
    jsx`<${ App } count=1 key=2> <//>`,
    document.querySelector('[react]')
);

Enter fullscreen mode Exit fullscreen mode

Give it a try to simplify and accelerate your development experience. There's also a previous late 2018 mention here on DEV.

On The Web Platform: Following several several years of using frameworks and libraries I realized the high cost associated with this Catholic-wedding approach, especially when something naturally changes like updates, etc. As a result I began focusing on what patterns and trends were actively evolving in native browser support. This based on the premise that in browsers, the engineering and vetting of solutions is of a higher caliber than the in-the-wild constantly maturing community. As a result those native solutions will tend to be more stable and longer lived, and a better investment long-term.

Top comments (0)

🌚 Browsing with dark mode makes you a better developer by a factor of exactly 40.

It's a scientific fact.