*This is the part2 of Creating Toast Message Component with useContext and React Portal.
You can read part 1 here.
After I defined React Portal, I went on to make a Toast Message Component with ClientPortal which I defined in part2.
Making Toast Message Component
const PortalToasty: React.FC<PortalToastyProps> = ({ show, text, error }) => {
return (
<>
{show && (
<ClientPortal selector="#myportal"> //wrap message component with ClientPortal
<div className="rounded-md fixed bg-lightGreen flex items-center shadow-md top-[50px] right-[50px]">
<div className=" flex items-center px-md justify-center">
{error ? (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth="1.5"
className="w-8 h-8 stroke-accentOrange"
>
<path
d="m9.75 9.75 4.5 4.5m0-4.5-4.5 4.5M2112a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
/>
</svg>
) : (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
strokeWidth="1.5"
className="w-8 h-8 stroke-accentOrange"
>
<path
d="M9 12.75 11.25 15 15 9.75M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
/>
</svg>
)}
</div>
<div className="bg-white h-full w-full py-md px-lg rounded-r-md">{text}</div>
</div>
</ClientPortal>
)}
</>
);
};
Wrap the component with ClientPortal
So that children component will be rendered into a DOM element referred to by "myportal", which I created in _document.tsx file like below.
export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Theme>
<Main />
<div id="myportal" />
<NextScript />
</Theme>
</body>
</Html>
);
}
Props
Three props are passed to this message component:
- show: Determines whether the component is visible or not.
- text: The message text to be displayed.
- error: Indicates the message type. If set to true, the component render error icon on the message.
CSS property
The first div element should have the 'position: fixed' property so that it is positioned relative to the viewport. In my case, I added 'top-[50px] right-[50px]' to position it in the top right corner of the viewport.
continue to part 3, where I define ToastMessageContext using useContext hook.
Cover photo credit:
from Unsplash
taken by Seriously Low Carb
Top comments (0)