기본 사용법
Grunfeld는 두 가지 주요 사용 패턴을 제공합니다: 간단한 알림과 사용자 응답을 받는 대화상자입니다. 각 패턴은 서로 다른 오버로드를 사용하여 구현됩니다.
알림 대화상자#
매개변수 없는 팩토리 함수를 사용하면 간단한 알림으로 동작합니다. 이 방식은 void를 반환하며 동기적으로 실행됩니다.
import { grunfeld } from "@ilokesto/grunfeld";
function MyComponent() {
const showAlert = () => {
// Simple alert - returns void
grunfeld.add(() => (
<div>
<p>Hello!</p>
<button onClick={() => grunfeld.remove()}>OK</button>
</div>
));
};
return <button onClick={showAlert}>Show Alert</button>;
}확인 대화상자#
사용자의 선택을 기다리는 확인 대화상자는 removeWith 함수를 매개변수로 받습니다. 이 함수를 호출하여 대화상자를 닫고 결과값을 반환합니다.
import { grunfeld } from "@ilokesto/grunfeld";
function MyComponent() {
const showConfirm = async () => {
const result = await grunfeld.add<boolean>((removeWith) => ({
element: (
<div>
<p>Are you sure you want to delete this?</p>
<button onClick={() => removeWith(true)}>Confirm</button>
<button onClick={() => removeWith(false)}>Cancel</button>
</div>
),
}));
if (result) {
console.log("User clicked confirm");
} else {
console.log("User clicked cancel");
}
};
return <button onClick={showConfirm}>Confirmation Dialog</button>;
}입력 대화상자#
사용자로부터 데이터를 입력받는 대화상자도 동일한 패턴을 따릅니다. 입력 컴포넌트를 만들고 removeWith를 통해 값을 전달합니다.
import { grunfeld } from "@ilokesto/grunfeld";
import { useState } from "react";
const InputDialog = ({ onClose }: { onClose: (name: string) => void }) => {
const [name, setName] = useState("");
return (
<div style={{ padding: "20px", background: "white", borderRadius: "8px" }}>
<h3>Enter your name</h3>
<input
autoFocus
type="text"
placeholder="Name"
value={name}
onChange={(e) => setName(e.target.value)}
onKeyDown={(e) =>
e.key === "Enter" && name.trim() && onClose(name.trim())
}
/>
<div>
<button
onClick={() => name.trim() && onClose(name.trim())}
disabled={!name.trim()}
>
OK
</button>
<button onClick={() => onClose("")}>Cancel</button>
</div>
</div>
);
};
function MyComponent() {
const showInput = async () => {
const input = await grunfeld.add<string>((removeWith) => ({
element: <InputDialog onClose={removeWith} />,
}));
if (input) {
console.log("Input value:", input);
} else {
console.log("Canceled");
}
};
return <button onClick={showInput}>Input Dialog</button>;
}