Background: I am trying to use sweetalert2-react-content to let me put a react <Link>
inside a Sweetalert2 footer
.
Generally speaking sweetalert2-react-content
is supposed to let you place react JSX into its fields, like this:
MySwal.fire({
text: "Fire fire",
footer: <div>Call the firebrigade</div>
});
... and indeed that sort of thing does work.
However, putting a <Link>
there does not work: it renders empty.
In this issue resolution message the the advice is "wrap your element in BrowserRouter
like this:
MySwal.fire({
html: (
<BrowserRouter>
...
</BrowserRouter>
),
})
Is this "legitimate"? What does it "mean" to have a BrowserRouter
inside an app that is routed using BrowserRouter
already?
No, it is an invariant violation to nest a router within another router. I think your situation is not a case of invalid nesting, but more to do with where sweetalert
is rendering the React JSX. From what I recall of sweetalert
it renders content outside the ReactTree.
You can certainly render more than one router, so long as they are not nested, but then the issue is that you've separate routing contexts that each individually handle routing/navigation, and navigating within one routing context doesn't update the others.
I suspect you could use a single custom history
reference and pass these to the routers you need, so they all reference the same history context internally.
react-router-dom@6
exports a HistoryRouter
for this purpose.
Example:
import { createBrowserHistory } from "history";
const history = createBrowserHistory({ window });
export default history;
...
import * as React from "react";
import * as ReactDOM from "react-dom";
import { unstable_HistoryRouter as HistoryRouter } from "react-router-dom";
import history from "../path/to/history";
ReactDOM.render(
<HistoryRouter history={history}>
{/* The rest of your app goes here */}
</HistoryRouter>,
root
);
...
import { unstable_HistoryRouter as HistoryRouter } from "react-router-dom";
import history from "../path/to/history";
MySwal.fire({
html: (
<HistoryRouter history={history}>
...
</HistoryRouter>
),
})
Note about unstable_HistoryRouter
:
This API is currently prefixed as
unstable_
because you may unintentionally add two versions of thehistory
library to your app, the one you have added to your package.json and whatever version React Router uses internally. If it is allowed by your tooling, it's recommended to not add history as a direct dependency and instead rely on the nested dependency from the react-router package. Once we have a mechanism to detect mis-matched versions, this API will remove itsunstable_
prefix.