Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for custom root element #36

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,19 @@ const CustomNotificationWithTheme = withTheme(CustomNotification);
toaster.notify(() => <CustomNotificationWithTheme title="I am pretty" />);
```

## Custom root element

By default all toasts will be rendered inside a `<div id="react-toast" />` appended dynamically to `<body>`.

You can control where you want to append this element by using the `setRoot` API:

```
const toastRoot = document.querySelector("main");

toaster.setRoot(toastRoot);
toaster.notify("Hello World from custom root");
```

## Contributors

- [Einar Löve](https://github.com/einarlove)
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "toasted-notes",
"version": "3.2.0",
"version": "3.3.0",
"description": "Flexible, easy to implement toast notifications for react",
"main": "commonjs/index.js",
"module": "lib/index.js",
Expand Down
17 changes: 12 additions & 5 deletions src/Alert/Toast.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ class Toaster {
removeAll?: Function;
closeToast?: Function;

constructor() {
if (!isBrowser) {
private didInit: boolean = false;

setRoot = (root: HTMLElement) => {
if (!isBrowser || this.didInit) {
return;
}

Expand All @@ -26,8 +28,9 @@ class Toaster {
const el = document.createElement("div");
el.id = PORTAL_ID;
el.className = "Toaster";
if (document.body != null) {
document.body.appendChild(el);
if (root != null) {
root.appendChild(el);
this.didInit = true
}
portalElement = el;
}
Expand All @@ -51,13 +54,17 @@ class Toaster {
};

notify = (message: MessageProp, options: MessageOptionalOptions = {}) => {
if (!this.didInit && isBrowser) {
this.setRoot(document.body)
}

if (this.createNotification) {
return this.createNotification(message, options);
}
};

close = (id: number, position: PositionsType) => {
if(this.closeToast){
if (this.closeToast) {
this.closeToast(id, position);
}
}
Expand Down