common util for toaster message from React-toastify

41 Views Asked by At

I am using React-toastify library, I am creating a common method in 'Util' file where we want to call just method with 'title' and 'description' so that 'toaster' notification message will be displayed in the UI from whichever component we want to show the toaster message.

My problem is Toaster message is showing and working fine but I am unable to customize the message with HTML elements like ',' within the message and those HTML tags are showing as it is in the notification message like below:

enter image description here

index.tsx:

const notify = () => {
  const notifyMsg = {type: 'success',title:"Toaster banner title", description:"Description This is the description part you can add your content here."};
  showToaster(notifyMsg);
}

const index = () => {
  return (
   ---------
   <button onClick={notify}>test</button>
   ----
   ------
   <ToastContainer transition={Slide} autoClose={false} position="bottom-right" style={{ height: "100px", width: "500px" }} />
   ------------
   ---------
}

src/utils/Common.ts

export function showToaster({ type = '', title, description }) {
  const toasterMsg = `<div><h5>${title}</h5>${description}</div>`;
  let toaster = "";
  switch(type){
    case 'success':
      return toast.success(dangerouslySetInnerHTML={{__html: toasterMsg}});
      break;
    case 'fail':
      return toast.error(toasterMsg);
      break;
    case 'warn':
      return toast.warn(toasterMsg);
      break;
    default:
      return toast(toasterMsg, {style:{ background: '#fff2df'}});
 }

I have tried to use 'dangerouslySetInnerHTML' method but it will work only in 'JSX' so I am unable to fix this HTML with content to display toaster notification.

Can anyone Please help in this regard..!

1

There are 1 best solutions below

2
SS87 On

You probably want the custom toast, added in v2.0. React-Hot-Toast Docs: Toasts

The default toasts (success, error, etc) return a string - if you hover over the method in TypeScript it will show you the type information, as you can see in this codepen if you hover over 'success' on the toast.success.

React-Hot-Toast Demo CodePen

Anything you pass is going to be treated as, and end up becoming, a string. Not HTML/JSX. The custom toast however does allow you pass in HTML/JSX, as it shows in the documentation.

I see in your code you're trying to render an H5 tag in the toast. If you're doing this just for the styling aspect - semantically putting heading tags in toasts seems a bit iffy - then you may not need the custom toast at all, and instead you could just pass through a particular class, either globally for the toast type or just in a singular instance (the documentation covers this).