|
| 1 | +import React, { useEffect, useState, useRef } from 'react'; |
| 2 | + |
| 3 | +const BasicEditor: React.FC = () => { |
| 4 | + const [checker, setChecker] = useState({ html: true, css: false, js: false }); |
| 5 | + const [html, setHtml] = useState(""); |
| 6 | + const [css, setCss] = useState(""); |
| 7 | + const [js, setJs] = useState(""); |
| 8 | + const iframeRef = useRef<HTMLIFrameElement | null>(null); |
| 9 | + |
| 10 | + useEffect(() => { |
| 11 | + if (!iframeRef.current) { |
| 12 | + alert("iframeRef is not available"); |
| 13 | + return; |
| 14 | + } |
| 15 | + |
| 16 | + const iframe = iframeRef.current; |
| 17 | + const document = iframe.contentDocument; |
| 18 | + |
| 19 | + if (!document) { |
| 20 | + alert("iframe contentDocument is not available"); |
| 21 | + return; |
| 22 | + } |
| 23 | + |
| 24 | + const documentContents = ` |
| 25 | + <!DOCTYPE html> |
| 26 | + <html lang="en"> |
| 27 | + <head> |
| 28 | + <style>${css}</style> |
| 29 | + </head> |
| 30 | + <body> |
| 31 | + ${html} |
| 32 | + <script>${js}</script> |
| 33 | + </body> |
| 34 | + </html> |
| 35 | + `; |
| 36 | + |
| 37 | + document.open(); |
| 38 | + document.write(documentContents); |
| 39 | + document.close(); |
| 40 | + }, [html, css, js]); |
| 41 | + |
| 42 | + return ( |
| 43 | + <div className='normal_editor'> |
| 44 | + <div className='editor_box'> |
| 45 | + <div className='editor_nav'> |
| 46 | + <button className={!checker.html ? 'btn_activated html' : 'btn_deactivated'} onClick={() => setChecker({ html: true, css: false, js: false })}>HTML</button> |
| 47 | + <button className={!checker.css ? 'btn_activated css' : 'btn_deactivated'} onClick={() => setChecker({ html: false, css: true, js: false })}>CSS</button> |
| 48 | + <button className={!checker.js ? 'btn_activated js' : 'btn_deactivated'} onClick={() => setChecker({ html: false, css: false, js: true })}>JS</button> |
| 49 | + </div> |
| 50 | + <textarea className={checker.html ? 'editor_textarea_activate' : 'editor_textarea_deactivate'} value={html} placeholder="HTML" onChange={(e) => setHtml(e.target.value)}></textarea> |
| 51 | + <textarea className={checker.css ? 'editor_textarea_activate' : 'editor_textarea_deactivate'} value={css} placeholder="CSS" onChange={(e) => setCss(e.target.value)}></textarea> |
| 52 | + <textarea className={checker.js ? 'editor_textarea_activate' : 'editor_textarea_deactivate'} value={js} placeholder="JavaScript" onChange={(e) => setJs(e.target.value)}></textarea> |
| 53 | + </div> |
| 54 | + <iframe ref={iframeRef} className='output_container' id="preview"></iframe> |
| 55 | + </div> |
| 56 | + ); |
| 57 | +} |
| 58 | + |
| 59 | +export default BasicEditor; |
0 commit comments