Code Editor - Copy this React, Tailwind Component to your project
Import { useState, useEffect } from "react"; import Editor from "@monaco editor/react"; const CodeEditor = () => { const [code, setCode] = useState("// Write your C code here"); const [inputs, setInputs] = useState([]); const [result, setResult] = useState(""); const [topic, setTopic] = useState("Provide the required inputs for the program:"); const [isLoading, setIsLoading] = useState(false); const [isSubmitDisabled, setIsSubmitDisabled] = useState(true); // Disable submit button initially const parseCodeForInputs = () => { const scanfRegex = /scanf\((.*?)\);/g; const printfRegex = /printf\((.*?)\);/g; const scanfMatches = [...code.matchAll(scanfRegex)]; const printfMatches = [...code.matchAll(printfRegex)]; const detectedInputs = scanfMatches.map((match, index) => { const precedingPrintf = printfMatches[index] ? printfMatches[index][1] .replace(/["']/g, "") // Remove quotes .replace(/\\n/g, "") // Remove \n characters .trim() : `Input ${index + 1}`; return { label: precedingPrintf, value: "" }; }); setInputs(detectedInputs); }; useEffect(() => { parseCodeForInputs(); }, [code]); // Check if all inputs are filled useEffect(() => { const allInputsFilled = inputs.every((input) => input.value.trim() !== ""); setIsSubmitDisabled(!allInputsFilled); }, [inputs]); const handleInputChange = (index, value) => { const updatedInputs = [...inputs]; updatedInputs[index].value = value; setInputs(updatedInputs); }; const handleSubmit = async () => { setIsLoading(true); setResult(""); try { const inputValues = inputs.map((input) => input.value).join("\n"); const response = await fetch("/api/compile", { method: "POST", headers: { "Content Type": "application/json", }, body: JSON.stringify({ code, input: inputValues }), }); const data = await response.json(); if (response.ok) { setResult(data.output || "Execution completed with no output."); } else { setResult(data.error || "An unknown error occurred."); } } catch (error) { setResult("Error: Unable to submit code."); } setIsLoading(false); }; return ( <div className="w screen h screen bg gradient to br from gray 900 to gray 800 p 5 flex items center justify center"> <div className="w full h full bg white rounded xl shadow 2xl overflow hidden flex flex col"> <header className="p 6 border b bg gray 100"> <h1 className="text 3xl font bold text gray 800">C Code Compiler</h1> </header> <div className="flex grow grid grid cols 2 gap 4 p 6"> {/* Code Editor */} <div className="bg gray 50 rounded lg overflow hidden"> <Editor height="100%" defaultLanguage="c" value={code} onChange={(value) => setCode(value || "")} theme="vs dark" options={{ minimap: { enabled: false }, fontSize: 20, scrollBeyondLastLine: false, automaticLayout: true, }} className="border rounded lg" /> </div> {/* Input and Output Section */} <div className="space y 4 flex flex col"> {/* Topic Section */} <div className="bg gray 100 p 4 rounded lg border border gray 200"> <h2 className="text lg font semibold text gray 800">{topic}</h2> </div> {/* Dynamically Generated Inputs */} {inputs.map((input, index) => ( <div key={index} className="flex flex col"> <label className="text gray 800 font medium mb 2"> {input.label}: </label> <input type="text" className="w full p 3 bg gray 50 border border gray 300 rounded lg focus:ring 2 focus:ring blue 500 focus:border transparent transition all duration 200 ease in out" value={input.value} onChange={(e) => handleInputChange(index, e.target.value)} placeholder={`Enter value for ${input.label}`} /> </div> ))} {/* Submit Button */} <div className="flex justify end"> <button className={`px 6 py 3 rounded lg font semibold text white transition all duration 200 ease in out ${isSubmitDisabled || isLoading ? "bg gray 500 cursor not allowed" : "bg blue 600 hover:bg blue 700 active:transform active:scale 95"} }`} onClick={handleSubmit} disabled={isSubmitDisabled || isLoading} > {isLoading ? ( <div className="flex items center"> <svg className="animate spin ml 1 mr 3 h 5 w 5 text white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" > <circle className="opacity 25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" ></circle> <path className="opacity 75" fill="currentColor" d="M4 12a8 8 0 018 8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3 2.647z" ></path> </svg> Running... </div> ) : ( "Submit" )} </button> </div> {/* Output Section */} <div className="flex grow bg gray 50 rounded lg p 6 border border gray 200 overflow auto"> <h2 className="text xl font bold text gray 800 mb 4">Output:</h2> {/* Show Program Output */} <div> <h3 className="text lg font semibold text gray 700">Program Output:</h3> <pre className="bg gray 100 p 4 rounded lg text sm font mono whitespace pre wrap overflow auto"> {result || "Your program output will appear here..."} </pre> </div> </div> </div> </div> </div> </div> ); }; export default CodeEditor; responsive this
