sweetalert2 / sweetalert2-react-content

Official SweetAlert2 enhancer adding support for React elements as content
MIT License
695 stars 47 forks source link

Next/Link isn't working. #172

Closed meotimdihia closed 3 years ago

meotimdihia commented 3 years ago

Next/Link isn't working. This is an example:

https://codesandbox.io/s/next-sweetalert2-bug-example-3rx84

chrome_2021-07-07_01-05-02

Related with the issue: https://github.com/vercel/next.js/issues/16864

I don't really know If this is package or next.js problem.

zenflow commented 3 years ago

@meotimdihia You can't use the Next/Link component in Sweetalert2 React content because that content is not part of the Next.js page (element tree). The Next.js page is rendered in the context of the Next.js router, but the Sweetalert2 React content is not. The Next/Link component relies on having the Next.js router in context.

I suggest that instead of using Next/Link you handle the <a> element's onClick event by calling the Router.push() method:

import Router from "next/router";
<a
  href="/day"
  onClick={(e) => {
    e.preventDefault();
    Router.push("/day");
    MySwal.close();
  }}
  className="font-semibold link"
>

https://codesandbox.io/s/next-sweetalert2-bug-example-forked-df89o?file=/pages/index.js

Of course to make things DRY and to separate concerns you could make a component for this.

zenflow commented 3 years ago

Closing because there's no action that can be taken in this project.

That said, it would be great if Next/Link used the singleton Router directly instead of getting it from context. (But there may be some reason for that)

meotimdihia commented 3 years ago

Thanks for the solution. I am fine with using the next/router.