Created
September 23, 2022 06:50
-
-
Save CallumHoward/07fc4604443363d6e917d0b324998b97 to your computer and use it in GitHub Desktop.
Example JSX file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from "react"; | |
export function Editor() { | |
const [state, setState] = useState([true, false, true]); | |
useEffect(() => { | |
const ydoc = new Y.Doc(); //create a ydoc | |
let provider = null; | |
try { | |
provider = new WebrtcProvider("Any Room Name", ydoc, { | |
//Remember the other tab or | |
//other user should be in same room for seeing real-time changes | |
signaling: [ | |
"wss://signaling.yjs.dev", | |
"wss://y-webrtc-signaling-eu.herokuapp.com", | |
"wss://y-webrtc-signaling-us.herokuapp.com", | |
], | |
}); | |
const yArray = ydoc.getArray("ieditortest"); | |
yArray.insert(0, state); | |
yArray.observe((event) => { | |
console.log("LOG: ", yArray.slice(-3)); | |
}); | |
const awareness = provider.awareness; //awareness is what makes other user aware about your actions | |
const color = RandomColor(); //Provied any random color to be used for each user | |
awareness.setLocalStateField("user", { | |
name: "Users Name", | |
color: color, | |
}); | |
} catch (err) { | |
alert("error in collaborating try refreshing or come back later !"); | |
} | |
return () => { | |
if (provider) { | |
provider.disconnect(); //We destroy doc we created and disconnect | |
ydoc.destroy(); //the provider to stop propagting changes if user leaves editor | |
} | |
}; | |
}); | |
return ( | |
<div | |
style={{ | |
display: "flex", | |
height: "100%", | |
width: "100%", | |
fontSize: "20px", | |
overflowY: "auto", | |
}} | |
> | |
{state.map((value, index) => ( | |
<button | |
key={index} | |
style={{background: value ? "green" : "grey"}} | |
onClick={() => { | |
const newState = [...state]; | |
newState[index] = !value; | |
setState(newState); | |
}} | |
> | |
{value} | |
</button> | |
))} | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment