Skip to content

Instantly share code, notes, and snippets.

@ZhaoMuwei
Last active December 7, 2021 11:09
Show Gist options
  • Select an option

  • Save ZhaoMuwei/b8321499d6283d84bb3b5ead1a206e46 to your computer and use it in GitHub Desktop.

Select an option

Save ZhaoMuwei/b8321499d6283d84bb3b5ead1a206e46 to your computer and use it in GitHub Desktop.
Simple wrapper for react-codemirror2 to make it work well with Antd(Version 3.x) form component(<Form>).
import React from "react";
// antd version 3.26
import {Form} from "antd";
// react-codemirror2 version 7.2.1
import {Controlled as CodeMirror} from "react-codemirror2";
import CodeMirrorWrapper from "./CodeMirrorWrapper";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/material.css";
class App extends React.Component {
render() {
return (
<div className="wrapper">
<Form>
<Form.Item label="๐Ÿ‘Ž Below's a code mirror that's NOT working">
{this.props.form.getFieldDecorator("content1", {
initialValue: "I'm not working well."
})(
<CodeMirror options={{ theme: "material" }} />
)}
</Form.Item>
<br />
<Form.Item label="๐Ÿ‘ This one's working fine">
{this.props.form.getFieldDecorator("content2", {
initialValue: "I'm working fine."
})(
<CodeMirrorWrapper options={{ theme: "material" }} />
)}
</Form.Item>
</Form>
</div>
);
}
}
export default Form.create()(App)
import React from "react";
import {Controlled as CodeMirror} from "react-codemirror2";
class CodeMirrorWrapper extends React.Component {
handleChange = (editor, data, value) => {
this.props.onChange(value)
};
render() {
// Antd's getFieldDecorator needs value & onChange
// https://3x.ant.design/components/form-cn/#this.props.form.getFieldDecorator(id,-options)
const {value, onChange, ...restProps} = this.props;
return (
<CodeMirror
value={value}
onBeforeChange={this.handleChange}
{...restProps}
/>
);
}
}
export default CodeMirrorWrapper
@ZhaoMuwei
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment