0. Offical Document
https://github.com/yjs/yjs/blob/master/README.md
1. Getting Started
1.1 Create Template Project
1
| pnpm create vite@latest yjs-demo --template react-ts
|
1.2 Remove Useless File
1.3 Create React Functional Components
src/components/CollaborativeDoc.tsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| import React, { useEffect, useRef, useState } from 'react' import * as Y from "yjs"; import { WebsocketProvider } from 'y-websocket';
const yDoc = new Y.Doc(); const yText = yDoc.getText("shared-text");
const wsProvider = new WebsocketProvider( "ws://localhost:1234", "my-room", yDoc, )
export default function CollaborativeDoc() { const [text, setText] = useState(yText.toString()); const textAreaRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => { const updateText = () => { setText(yText.toString()); }
yText.observe(updateText)
return () => { yText.unobserve(updateText); } }, []);
const handleInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => { yText.delete(0, yText.length); yText.insert(0, event.target.value); }
return ( <div> <textarea ref={textAreaRef} value={text} onChange={handleInputChange} rows={10} cols={10} ></textarea> </div> ) }
|
src/App.tsx
1 2 3 4 5 6 7 8 9 10 11 12
| import CollaborativeDoc from './components/CollaborativeDoc'
function App() { return ( <div> <CollaborativeDoc /> </div> ) }
export default App
|
1.4 Run Project
Start y-websocket Server:
Start project
