Zurück zu blog
06. Feb. 2025
2 Minuten Lesezeit

React - Dialog Fenster (Modal)

Ich habe gelernt, wie sich in React Dialog Fenster erstellen lassen.
//ResultModal.jsx
export default function ResultModal({ result, targetTime }) {

    return <dialog className="result-modal" open>
        <h2>You {result}</h2>
        <p>The target time was <strong>{targetTime} seconds.</strong></p>
        <p>You stopped the timer with <strong>X seconds left.</strong></p>
        <form method="dialog">
            <button>Close</button>
        </form>
    </dialog>;
}

Toastbar für Fehlermeldung bzw. Erfolgsmeldungen

//App.jsx
import Toast from './Toast';
import { useState } from "react";

function App() {
  const [toastVisible, setToastVisible] = useState(false);
  function handleEnrol() {
    setToastVisible(true);
    setTimeout(() => {
      setToastVisible(false);
    }, 3000);
  }
  return (
    <div id="app">
      {toastVisible && <Toast message="Enrolled successfully!" />}
      <article>
        <h2>React Course</h2>
        <p>
          A course that teaches you React from the ground up and in great depth!
        </p>
        <button onClick={handleEnrol}>Enrol</button>
      </article>
    </div>
  );
}
export default App;
//Toast.jsx
import { createPortal } from 'react-dom';
export default function Toast({ message }) {
    return createPortal(
      <aside className="toast" data-testid="toast">
        <p>{message}</p>
      </aside>,
      document.querySelector('body')
    );
}