Skip to content

An opinionated toast component for React.

feat: allow setting position when creating a toast (#134)

Stephen Zhouceb7b63d69b4
diff --git a/src/index.tsx b/src/index.tsx
index 473aceb..1060577 100644
--- a/src/index.tsx
+++ b/src/index.tsx
@@ -399,6 +399,11 @@ const Toaster = (props: ToasterProps) => {
dir = getDocumentDirection(),
} = props;
const [toasts, setToasts] = React.useState<ToastT[]>([]);
+ const possiblePositions = React.useMemo(() => {
+ return Array.from(
+ new Set([position].concat(toasts.filter((toast) => toast.position).map((toast) => toast.position))),
+ );
+ }, [toasts, position]);
const [heights, setHeights] = React.useState<HeightT[]>([]);
const [expanded, setExpanded] = React.useState(false);
const [interacting, setInteracting] = React.useState(false);
@@ -411,7 +416,6 @@ const Toaster = (props: ToasterProps) => {
: 'light'
: 'light',
);
- const [y, x] = position.split('-');
const listRef = React.useRef<HTMLOListElement>(null);
const hotkeyLabel = hotkey.join('+').replace(/Key/g, '').replace(/Digit/g, '');
@@ -525,83 +529,93 @@ const Toaster = (props: ToasterProps) => {
return (
// Remove item from normal navigation flow, only available via hotkey
<section aria-label={`Notifications ${hotkeyLabel}`} tabIndex={-1}>
- <ol
- dir={dir === 'auto' ? getDocumentDirection() : dir}
- tabIndex={-1}
- ref={listRef}
- className={className}
- data-sonner-toaster
- data-theme={actualTheme}
- data-rich-colors={richColors}
- data-y-position={y}
- data-x-position={x}
- style={
- {
- '--front-toast-height': `${heights[0]?.height}px`,
- '--offset': typeof offset === 'number' ? `${offset}px` : offset || VIEWPORT_OFFSET,
- '--width': `${TOAST_WIDTH}px`,
- '--gap': `${GAP}px`,
- ...style,
- } as React.CSSProperties
- }
- onBlur={(event) => {
- if (isFocusWithinRef.current && !event.currentTarget.contains(event.relatedTarget)) {
- isFocusWithinRef.current = false;
- if (lastFocusedElementRef.current) {
- lastFocusedElementRef.current.focus({ preventScroll: true });
- lastFocusedElementRef.current = null;
+ {possiblePositions.map((position, index) => {
+ const [y, x] = position.split('-');
+ return (
+ <ol
+ key={position}
+ dir={dir === 'auto' ? getDocumentDirection() : dir}
+ tabIndex={-1}
+ ref={listRef}
+ className={className}
+ data-sonner-toaster
+ data-theme={actualTheme}
+ data-rich-colors={richColors}
+ data-y-position={y}
+ data-x-position={x}
+ style={
+ {
+ '--front-toast-height': `${heights[0]?.height}px`,
+ '--offset': typeof offset === 'number' ? `${offset}px` : offset || VIEWPORT_OFFSET,
+ '--width': `${TOAST_WIDTH}px`,
+ '--gap': `${GAP}px`,
+ ...style,
+ } as React.CSSProperties
}
- }
- }}
- onFocus={(event) => {
- const isNotDismissible = event.target instanceof HTMLElement && event.target.dataset.dismissible === 'false';
-
- if (isNotDismissible) return;
-
- if (!isFocusWithinRef.current) {
- isFocusWithinRef.current = true;
- lastFocusedElementRef.current = event.relatedTarget as HTMLElement;
- }
- }}
- onMouseEnter={() => setExpanded(true)}
- onMouseMove={() => setExpanded(true)}
- onMouseLeave={() => {
- // Avoid setting expanded to false when interacting with a toast, e.g. swiping
- if (!interacting) {
- setExpanded(false);
- }
- }}
- onPointerDown={(event) => {
- const isNotDismissible = event.target instanceof HTMLElement && event.target.dataset.dismissible === 'false';
-
- if (isNotDismissible) return;
- setInteracting(true);
- }}
- onPointerUp={() => setInteracting(false)}
- >
- {toasts.map((toast, index) => (
- <Toast
- key={toast.id}
- index={index}
- toast={toast}
- duration={duration}
- className={toastOptions?.className}
- descriptionClassName={toastOptions?.descriptionClassName}
- invert={invert}
- visibleToasts={visibleToasts}
- closeButton={closeButton}
- interacting={interacting}
- position={position}
- style={toastOptions?.style}
- removeToast={removeToast}
- toasts={toasts}
- heights={heights}
- setHeights={setHeights}
- expandByDefault={expand}
- expanded={expanded}
- />
- ))}
- </ol>
+ onBlur={(event) => {
+ if (isFocusWithinRef.current && !event.currentTarget.contains(event.relatedTarget)) {
+ isFocusWithinRef.current = false;
+ if (lastFocusedElementRef.current) {
+ lastFocusedElementRef.current.focus({ preventScroll: true });
+ lastFocusedElementRef.current = null;
+ }
+ }
+ }}
+ onFocus={(event) => {
+ const isNotDismissible =
+ event.target instanceof HTMLElement && event.target.dataset.dismissible === 'false';
+
+ if (isNotDismissible) return;
+
+ if (!isFocusWithinRef.current) {
+ isFocusWithinRef.current = true;
+ lastFocusedElementRef.current = event.relatedTarget as HTMLElement;
+ }
+ }}
+ onMouseEnter={() => setExpanded(true)}
+ onMouseMove={() => setExpanded(true)}
+ onMouseLeave={() => {
+ // Avoid setting expanded to false when interacting with a toast, e.g. swiping
+ if (!interacting) {
+ setExpanded(false);
+ }
+ }}
+ onPointerDown={(event) => {
+ const isNotDismissible =
+ event.target instanceof HTMLElement && event.target.dataset.dismissible === 'false';
+
+ if (isNotDismissible) return;
+ setInteracting(true);
+ }}
+ onPointerUp={() => setInteracting(false)}
+ >
+ {toasts
+ .filter((toast) => (!toast.position && index === 0) || toast.position === position)
+ .map((toast, index) => (
+ <Toast
+ key={toast.id}
+ index={index}
+ toast={toast}
+ duration={duration}
+ className={toastOptions?.className}
+ descriptionClassName={toastOptions?.descriptionClassName}
+ invert={invert}
+ visibleToasts={visibleToasts}
+ closeButton={closeButton}
+ interacting={interacting}
+ position={position}
+ style={toastOptions?.style}
+ removeToast={removeToast}
+ toasts={toasts}
+ heights={heights}
+ setHeights={setHeights}
+ expandByDefault={expand}
+ expanded={expanded}
+ />
+ ))}
+ </ol>
+ );
+ })}
</section>
);
};
diff --git a/src/types.ts b/src/types.ts
index 5dbf965..fffbf6e 100644
--- a/src/types.ts
+++ b/src/types.ts
@@ -37,6 +37,7 @@ export interface ToastT {
style?: React.CSSProperties;
className?: string;
descriptionClassName?: string;
+ position?: Position;
}
export type Position = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right' | 'top-center' | 'bottom-center';
diff --git a/website/app/page.tsx b/website/app/page.tsx
index c77164b..2f6a9b1 100644
--- a/website/app/page.tsx
+++ b/website/app/page.tsx
@@ -8,7 +8,7 @@ import { Hero } from '@/src/components/Hero';
import { Types } from '@/src/components/Types/Types';
import { ExpandModes } from '@/src/components/ExpandModes';
import { Footer } from '@/src/components/Footer';
-import { Position } from '@/src/components/Position';
+import { DynamicPosition, Position } from '@/src/components/Position';
import { Usage } from '@/src/components/Usage';
import { Other } from '@/src/components/Other/Other';
@@ -28,6 +28,7 @@ export default function Home() {
<Usage />
<Types />
<Position position={position} setPosition={setPosition} />
+ <DynamicPosition />
<ExpandModes expand={expand} setExpand={setExpand} />
<Other setCloseButton={setCloseButton} setRichColors={setRichColors} />
</div>
diff --git a/website/src/components/Position/index.tsx b/website/src/components/Position/index.tsx
index 6b6d9f3..8fe9e77 100644
--- a/website/src/components/Position/index.tsx
+++ b/website/src/components/Position/index.tsx
@@ -1,5 +1,6 @@
import { toast } from 'sonner';
import { CodeBlock } from '../CodeBlock';
+import React from 'react';
const positions = ['top-left', 'top-center', 'top-right', 'bottom-left', 'bottom-center', 'bottom-right'] as const;
@@ -41,3 +42,36 @@ export const Position = ({
</div>
);
};
+
+export const DynamicPosition = () => {
+ const [currentPosition, setCurrentPosition] = React.useState<Position>('bottom-right');
+ return (
+ <div>
+ <h2>Dynamic Position</h2>
+ <p>
+ You can change the position of the toast dynamically by passing a <code>position</code> prop to the toast
+ function.
+ </p>
+ <div className="buttons">
+ {positions.map((position) => (
+ <button
+ className="button"
+ data-active={position === currentPosition}
+ onClick={() => {
+ setCurrentPosition(position);
+ toast('Event has been created', {
+ position,
+ });
+ }}
+ key={position}
+ >
+ {position}
+ </button>
+ ))}
+ </div>
+ <CodeBlock>{`toast('Event has been created', {
+ position: '${currentPosition}',
+})`}</CodeBlock>
+ </div>
+ );
+};