breatheco-de / breatheco-de

https://breatheco-de.vercel.app
1.2k stars 2.44k forks source link

Agregar funcionalidad de preview para lenguajes html, css y vanillajs #7985

Closed alesanchezr closed 1 week ago

alesanchezr commented 1 week ago

Puedes inspirarte en este codigo:

import React, { useState } from "react";

const CodePreview = () => {
  // State to store user inputs
  const [html, setHtml] = useState("");
  const [css, setCss] = useState("");
  const [js, setJs] = useState("");

  // Create the complete HTML document
  const generatePreview = () => {
    return `
      <html>
        <head>
          <style>${css}</style>
        </head>
        <body>
          ${html}
          <script>${js}</script>
        </body>
      </html>
    `;
  };

  // Check whether the preview should be displayed
  const shouldShowPreview = html.trim() !== "" || js.trim() !== "";

  return (
    <div>
      {/* Input areas */}
      <div>
        <h2>HTML</h2>
        <textarea
          value={html}
          onChange={(e) => setHtml(e.target.value)}
          rows="5"
          cols="50"
          placeholder="Write HTML here"
        />
      </div>
      <div>
        <h2>CSS</h2>
        <textarea
          value={css}
          onChange={(e) => setCss(e.target.value)}
          rows="5"
          cols="50"
          placeholder="Write CSS here"
        />
      </div>
      <div>
        <h2>JavaScript</h2>
        <textarea
          value={js}
          onChange={(e) => setJs(e.target.value)}
          rows="5"
          cols="50"
          placeholder="Write JavaScript here"
        />
      </div>

      {/* Conditionally render the preview */}
      {shouldShowPreview ? (
        <>
          <h2>Preview</h2>
          <iframe
            title="Live Preview"
            srcDoc={generatePreview()} // Dynamically inject content
            sandbox="allow-scripts"
            style={{ width: "100%", height: "300px", border: "1px solid black" }}
          />
        </>
      ) : (
        <p>Provide HTML or JavaScript to see the preview.</p>
      )}
    </div>
  );
};

export default CodePreview;
gustavomm19 commented 1 week ago

It can be tested here: https://app-git-fork-gustavomm19-code-preview-geeksacademy.vercel.app/es/lesson/fake-tomas-code-viewer