DEV Community

CitronBrick
CitronBrick

Posted on • Edited on

Future React Components: ES2022

Hi, here's an accessible checkbox, which is probably the web's 1st React Component, created using ES2022.

Here the state is a private instance variable. Private instance variables, prefixed with #, are supported in ES2022.

class Checkbox extends React.Component {

        #state = {checked: false};

        handleClick=(evt)=>{
            this.setState((state)=>
                ({checked: !state.checked})
            );
        }

        handleKeyDown=(evt)=>{
            if([' ','Enter'].includes(evt.key)) {
                this.handleClick();
            }
        }

        render() {
            return <div className="checkbox" 
                id={this.props.id} 
                role="checkbox" 
                aria-checked={this.state.checked} 
                aria-disabled={this.props.disabled} 
                onClick={this.handleClick} 
                onKeyDown={this.handleKeyDown} 
                tabIndex={!this.props.disabled? "0":null}>
                    {this.state.checked ? "":""}
            </div>
        }

    }
Enter fullscreen mode Exit fullscreen mode

Unfortunately the latest Babel version (7.0.0-beta.3), does not support it yet (14 July 2022). We'll have to wait, before using it with JSX.

If you don't like creating components using the class keyword, here's another article that shows how to create class compomnents without it. (Internet Explorer 11 compatible)

Top comments (0)