Search code examples
javascriptreactjscodemirrorreact-codemirror2

How to add close bracket and close tag for react code mirror


I'm using react-codemirror2 in a react project. I want to add features like auto bracket close and auto tag close. There is a npm package called @codemirror/closebrackets but I can't find any documentation to do that.

        <ControlledEditor
            onBeforeChange={handleChange}
            value={value}
            className="code-mirror-wrapper"
            options={{
                linerWrapping: true,
                lint: true,
                mode: language,
                theme: 'material',
                lineNumbers: true
            }}
        />

This is my react component. Specify if there is a way to do without additional packages like @codemirror/closebrackets.


Solution

  • You can add autoCloseBrackets: true to your options and it'll work fine. From the doc:

    Defines an option autoCloseBrackets that will auto-close brackets and quotes when typed.

    import 'codemirror/addon/edit/closebrackets'
    
    // other parts of the code//
    
    <ControlledEditor
                onBeforeChange={handleChange}
                value={value}
                className="code-mirror-wrapper"
                options={{
                    linerWrapping: true,
                    lint: true,
                    mode: language,
                    theme: 'material',
                    lineNumbers: true,
                    autoCloseBrackets: true,
                }}
            />