Research
Security News
Malicious npm Packages Inject SSH Backdoors via Typosquatted Libraries
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
react-codemirror2
Advanced tools
The react-codemirror2 package is a React component wrapper for CodeMirror, a versatile text editor implemented in JavaScript for the browser. It allows you to integrate CodeMirror into your React applications, providing a rich text editor with syntax highlighting, autocompletion, and other advanced features.
Basic Usage
This code demonstrates the basic usage of the react-codemirror2 package. It sets up a CodeMirror editor with JavaScript syntax highlighting and a material theme. The editor's value is controlled by React state.
import React from 'react';
import { Controlled as CodeMirror } from 'react-codemirror2';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material.css';
const MyEditor = () => {
const [value, setValue] = React.useState('');
return (
<CodeMirror
value={value}
options={{
mode: 'javascript',
theme: 'material',
lineNumbers: true
}}
onBeforeChange={(editor, data, value) => {
setValue(value);
}}
/>
);
};
export default MyEditor;
Event Handling
This code demonstrates how to handle events in the react-codemirror2 package. It logs messages to the console when the content changes or when the editor loses focus.
import React from 'react';
import { Controlled as CodeMirror } from 'react-codemirror2';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material.css';
const MyEditor = () => {
const [value, setValue] = React.useState('');
return (
<CodeMirror
value={value}
options={{
mode: 'javascript',
theme: 'material',
lineNumbers: true
}}
onBeforeChange={(editor, data, value) => {
setValue(value);
}}
onChange={(editor, data, value) => {
console.log('Content changed:', value);
}}
onBlur={(editor, event) => {
console.log('Editor lost focus');
}}
/>
);
};
export default MyEditor;
Custom Key Bindings
This code demonstrates how to set custom key bindings in the react-codemirror2 package. It uses the 'sublime' keymap for the CodeMirror editor.
import React from 'react';
import { Controlled as CodeMirror } from 'react-codemirror2';
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material.css';
import 'codemirror/keymap/sublime';
const MyEditor = () => {
const [value, setValue] = React.useState('');
return (
<CodeMirror
value={value}
options={{
mode: 'javascript',
theme: 'material',
lineNumbers: true,
keyMap: 'sublime'
}}
onBeforeChange={(editor, data, value) => {
setValue(value);
}}
/>
);
};
export default MyEditor;
react-ace is a React component for the Ace editor. It provides similar functionalities to react-codemirror2, such as syntax highlighting, autocompletion, and customizable themes. However, it uses the Ace editor instead of CodeMirror, which may have different performance characteristics and feature sets.
react-monaco-editor is a React component for the Monaco editor, which is the editor that powers Visual Studio Code. It offers advanced features like IntelliSense, parameter hints, and a rich API for customization. Compared to react-codemirror2, it provides a more feature-rich editing experience but may have a steeper learning curve.
react-simple-code-editor is a lightweight code editor component for React. It provides basic syntax highlighting and editing capabilities using Prism.js. It is simpler and more lightweight compared to react-codemirror2, making it suitable for use cases where a full-fledged editor is not required.
demo @ scniro.github.io/react-codemirror2
npm install react-codemirror2 codemirror --save
react-codemirror2
ships with the notion of an uncontrolled and controlled component. UnControlled
consists of a simple wrapper largely powered by the inner workings of codemirror
itself, while Controlled
will demand state management from the user, preventing codemirror changes unless properly handled via value
. The latter will offer more control and likely be more appropriate with redux heavy apps.
import {UnControlled as CodeMirror} from 'react-codemirror2'
<CodeMirror
value='<h1>I ♥ react-codemirror2</h1>'
options={{
mode: 'xml',
theme: 'material',
lineNumbers: true
}}
onChange={(editor, data, value) => {
}}
/>
import {Controlled as CodeMirror} from 'react-codemirror2'
<CodeMirror
value={this.state.value}
options={options}
onBeforeChange={(editor, data, value) => {
this.setState({value});
}}
onChange={(editor, data, value) => {
}}
/>
codemirror
comes as a peer dependency, meaning you'll need to require it in your project in addition to react-codemirror2
. This prevents any versioning conflicts that would arise if codemirror
came as a dependency through this wrapper. It's been observed that version mismatches can cause difficult to trace issues such as syntax highlighting disappearing without any explicit errors/warnings
Since codemirror ships mostly unconfigured, the user is left with the responsibility for requiring any additional resources should they be necessary. This is often the case when specifying certain language modes and themes. How to import/require these assets will vary according to the specifics of your development environment. Below is a sample to include the assets necessary to specify a mode of xml
(HTML) and a material
theme.
note that the base codemirror.css file is required in all use cases
@import 'codemirror/lib/codemirror.css';
@import 'codemirror/theme/material.css';
import CodeMirror from 'react-codemirror2';
require('codemirror/mode/xml/xml');
require('codemirror/mode/javascript/javascript');
prop | type default | components | description |
---|---|---|---|
autoCursor | boolean true | Controlled UnControlled | should component cursor position correct when value changed |
autoScroll | boolean true | Controlled UnControlled | should component scroll cursor position into view when value changed |
className | string | Controlled UnControlled | pass through class class="react-codemirror2 className" |
defineMode | object | Controlled UnControlled | pass a custom mode via {name: 'custom', fn: myModeFn} |
detach | boolean | UnControlled | should component ignore new props |
options | object | Controlled UnControlled | codemirror configuration |
value | string | *Controlled UnControlled | * component value must be managed for controlled components |
cursor
- setCursorwill programmatically set cursor to the position specified
<CodeMirror
[...]
cursor={{
line: 5,
ch: 10
}}
onCursor={(editor, data) => {}}
/>
scroll
- scrollTowill programmatically scroll to the specified coordinate
<CodeMirror
[...]
scroll={{
x: 50,
y: 50
}}
onScroll={(editor, data) => {}}
/>
selection={{ranges: array<{anchor, head}>, focus?: boolean}
- setSelectionswill programmatically select the ranges specified
<CodeMirror
[...]
selection={{
ranges: [{
anchor: {ch: 8, line: 5},
head: {ch: 37, line: 5}
}],
focus: true // defaults false if not specified
}}
onSelection={(editor, data) => {}}
/>
event | components | description |
---|---|---|
editorDidAttach(editor) | UnControlled | component is now responding to new props |
editorDidConfigure(editor) | Controlled UnControlled | component configuration has been set |
editorDidDetach(editor) | UnControlled | component is now ignoring new props |
editorDidMount(editor, [next]) | Controlled UnControlled | * invoking optional next will trigger editorDidConfigure |
editorWillUnmount(editor) | Controlled UnControlled | invoked before componentWillUnmount |
onBeforeChange(editor, data, value, [next]) | Controlled UnControlled | * if used, next is returned via UnControlled and must be invoked to trigger onChange |
onChange(editor, data, value) | Controlled UnControlled | the component value has been changed |
onBlur(editor, event)
- bluronContextMenu(editor, event)
- contextmenuonCopy(editor)
- copyonCursor(editor, data)
- cursorActivityonCursorActivity(editor)
- cursorActivityonCut(editor)
- cutonDblClick(editor, event)
- dblclickonDragEnter(editor, event)
- dragenteronDragOver(editor, event)
- dragoveronDragLeave(editor, event)
- dragleaveonDragStart(editor, event)
- dragstartonDrop(editor, event)
- droponFocus(editor, event)
- focusonGutterClick(editor, lineNumber, gutter, event)
- gutterClickonInputRead(editor, changeObj)
- gutterClickonKeyDown(editor, event)
- keydownonKeyHandled(editor, key, event)
- keyhandledonKeyPress(editor, event)
- keypressonKeyUp(editor, event)
- keyuponMouseDown(editor, event)
- mousedownonPaste(editor)
- pasteonScroll(editor, data)
- scrollonSelection(editor, data)
- beforeSelectionChangeonTouchStart(editor, event)
- touchstartonUpdate(editor, event)
- updateonViewportChange(editor, from, to)
- viewportChangeYes. react-codemirror2 will prevent rendering in absence of navigator
. You can also force the component to not render via a PREVENT_CODEMIRROR_RENDER
global.
The recommended technique to get the instance is to persist the editor
returned via event callbacks. There is no static method to get it on demand, e.g. CodeMirror.getInstance()
. Example...
constructor() {
this.instance = null;
}
render() {
<CodeMirror editorDidMount={editor => { this.instance = editor }}/>
}
Check out bokuweb/re-resizable. Wrapping your component with <Resizable/>'s
works well
Pull Requests are welcome. Be mindful of the available scripts below to help submitting a well-received contribution.
npm run start
to run the app on localhost:8000
npm run test
to ensure tests continue to passnpm run build
to generate the demo bundlenote that it's necessary to bump the package.json version prior to final npm run build
so we can grab the proposed new version as seen in the demo header. Also note, the core changes are to be made in src/index.tsx
as ./index.js
and ./index.d.ts
are generated
FAQs
a tiny react codemirror component wrapper
The npm package react-codemirror2 receives a total of 158,169 weekly downloads. As such, react-codemirror2 popularity was classified as popular.
We found that react-codemirror2 demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Research
Security News
Socket’s threat research team has detected six malicious npm packages typosquatting popular libraries to insert SSH backdoors.
Security News
MITRE's 2024 CWE Top 25 highlights critical software vulnerabilities like XSS, SQL Injection, and CSRF, reflecting shifts due to a refined ranking methodology.
Security News
In this segment of the Risky Business podcast, Feross Aboukhadijeh and Patrick Gray discuss the challenges of tracking malware discovered in open source softare.