Simple Portal Toast
ReactJS
Hard
7 views
Problem Description
Create a Toast that renders at the end of body using createPortal.
Output Format
Render a React component.
Constraints
Use react-dom createPortal.
Official Solution
import React, { useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
function Toast({ open, message }) {
if (!open) return null;
return createPortal(
<div style={{ position: 'fixed', left: 16, right: 16, bottom: 16, maxWidth: 520, margin: '0 auto', background: '#111', color: '#fff', padding: '12px 14px', borderRadius: 14 }}>
{message}
</div>,
document.body
);
}
export default function App() {
const [open, setOpen] = useState(false);
useEffect(() => {
if (!open) return;
const t = setTimeout(() => setOpen(false), 1200);
return () => clearTimeout(t);
}, [open]);
return (
<div style={{ padding: 16 }}>
<button type='button' onClick={() => setOpen(true)} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>
Show toast
</button>
<Toast open={open} message='Saved on meetcode.' />
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!