To support multiple files or tabs (like an IDE), use the path prop on the Editor component. When a path is provided, the component checks if a model with that path already exists. If it does, it reuses the existing model (preserving undo stack, scroll position, and text selection); otherwise, it creates a new one.
Key Prop Behaviors:
defaultValue, defaultLanguage, and defaultPath: Used only during the initial creation of a new model.value, language, and path: Tracked and applied continuously.saveViewState: A boolean indicating whether to save the model's view state (scroll position, etc.) between model changes.
import React, { useState } from 'react';
import Editor from '@monaco-editor/react';
const files = {
'script.js': { name: 'script.js', language: 'javascript', value: 'console.log("hello");' },
'style.css': { name: 'style.css', language: 'css', value: 'body { color: red; }' },
};
function App() {
const [fileName, setFileName] = useState('script.js');
const file = files[fileName];
return (
<>
<button onClick={() => setFileName('script.js')}>script.js</button>
<button onClick={() => setFileName('style.css')}>style.css</button>
<Editor
height="80vh"
theme="vs-dark"
path={file.name}
defaultLanguage={file.language}
defaultValue={file.value}
/>
</>
);
}