timolins / react-hot-toast Goto Github PK
View Code? Open in Web Editor NEWSmoking Hot React Notifications ๐ฅ
Home Page: https://react-hot-toast.com
License: MIT License
Smoking Hot React Notifications ๐ฅ
Home Page: https://react-hot-toast.com
License: MIT License
When installing react-hot-toast
(or running npm install
in a project that already has react-hot-toast
) the following warning is shown:
npm WARN [email protected] requires a peer of csstype@^2.6.2 but none is installed. You must install peer dependencies yourself.
Documentation says nothing about need of csstype
.
Maybe react-hot-toast
should make it regular dependency if it's needed?
On the other note, there are users, who are using just headless mode, and they don't need neither goober
or csstype
.
I noticed a weird behavior when running a promise that takes fairly long (about 30s) the loading toast is automatically dismissed even before resolving the promise, when it's resolved the success toast appears.
Can you reproduce this? Try having a promise that takes about 30 or 40 seconds to execute.
toast.promise(subtitlesPromise, {
loading: 'Generating your subtitles, please wait...',
success: 'Subtitles generated!',
error: 'Error generating subtitles.',
});
Thanks Timo for this awesome library!
As the title suggests, is it possible to limit the number of toasts displayed to some integer value? So subsequent triggers of toast()
will be blocked. I did not come across anything in the docs which implied this, so I was wondering if there's any way to implement this. Thanks! (great package by the way!)
Is it possible to create a custom promise toast? I'd like to add a Dismiss button to all the toasts so I am using the custom toast mentioned in the documentation. However, when it comes to a custom promise toast, doesn't the promiseFunc()
passed in to the promise toast take the place of the custom toast function?
Is there a way in toast.promise(...)
to only show the success
/ error
toasts and not the loading toast? The current ways I see are to either set the duration to 0
or auto dismiss, which actually renders it for a second before it goes away. Can I configure it to just not show the loading toast in some scenarios?
Hi, I'm having an issue using toast.promise()
and I can't figure out what's wrong with my code. The loading
toast doesn't get displayed at all. The success
/error
toasts appear after the fetch is complete, all good here.
Weirdly, if I uncomment the toast("Hey")
(see code below) in the render function, then the loading toast is displayed too (there's also a number that appears on top of the page).
Steps to reproduce on a fresh React install:
src/App.js
:import React from "react";
import logo from "./logo.svg";
import "./App.css";
import toast, { Toaster } from "react-hot-toast";
const notify = () => toast("Here is your toast.");
class App extends React.Component {
componentDidMount() {
console.log("mounted");
// Random API from https://github.com/public-apis/public-apis
const fetchPromise = fetch(`https://randomfox.ca/floof/`);
toast.promise(fetchPromise, {
loading: "Loading",
success: "Got the data",
error: "Error when fetching",
});
}
render() {
return (
<div className="App">
{/* {toast("Hey")} */}
<Toaster />
<header className="App-header">
<button onClick={notify}>Make me a toast</button>
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;
Thanks
I'm trying to use the toast inside a view that is inside a modal, The full structure it's something like this:
<ModalBase>
<ModalOverlay>
<ModalBox>
<View>
</ ModalBox>
</ ModalOverlay>
</ ModalBase>
I want to use it inside view which is something like this:
<>
<Toaster position="bottom-center" />
<OtherContent>
...
<button onClick={handleClick} ... />
</ OtherContent>
</>
Where
handleClick = () => {
...
toast('test message');
}
Also I've tried with toast.success(...)
I'm importing like this: import toast, { Toaster } from 'react-hot-toast'; and I'm using typescript
For example, I want the toast to show at bottom-center
for mobile devices (width < 640px), but top-right
for laptop/desktop
Hi! Is it possible to provide any custom variants of toast with the headless mode? It would be great, if we could create Notifications
component and have own success
, error
and other toast's variants to use it, as:
toast.custom('My custom toast variant')
Hi, I have the Toaster set up like this:
in CreateBook.js
import React from 'react'
import { Link } from 'react-router-dom'
import toast, { Toaster } from 'react-hot-toast'
export default CreateBook() {
// something code
const handleSubmit = () => {
toast.success('Clicked!')
}
return (
<>
Something content...
<button onClick={handleSubmit}>Submit</button>
<Link to='/home' title='Home.js'>Home</Link>
<Toaster />
</>
)
}
in Home.js
import React from 'react'
import { Link } from 'react-router-dom'
import toast, { Toaster } from 'react-hot-toast'
export default Home() {
// something code
return (
<>
Something content...
<Link to='/create-book' title='CreateBook.js'>CreateBook</Link>
<Toaster />
</>
)
}
Toast component re-render when i quickly click the 'Home' link after I clicked the 'Submit' button.
How can I prevent this from happening?
Is there a similar method to toast.remove()
auto run when the CreateBook
component unmount?
I'd love to blur the header of my website while the toast is in viewport, just like your website! Thank you.
Is it possible to have a function to add functions or actions to the promise ?. For example if you want to redirect to a different url based on the success of the promise.
No matter where Toaster is placed its' position is relative to the main document, is there a way to make it relative to the specific container?
For example if I have this structure:
<div className='main'>
<div className='leftMenu'>
</div>
<div className='content'>
<Toaster />
</div>
</div>
and let's say leftMenu have 20% width and mainContent have 80% width, I wish centered toast would appear center to the 'content' - so 60% from left side of the screen, not relative to 'mainWrapper' (50% from left side of the screen).
I have an express api that returns an array with one element per each error.
Is it possible to display/pop up a toast for every element in an array?
API Response [ 'Email is required', 'Email is not valid', 'Password is required' ]
Currently using toast.promise()
I'm getting an issue where the *.d.ts file doesn't have a default export and I'm getting the next error:
ERROR in [at-loader] ./node_modules/react-hot-toast/dist/components/toaster.d.ts:2:8
TS1192: Module '"/.../node_modules/csstype/index"' has no default export.
Hi, Looks like when set duration of toast (for my case toast.error()
) it's not dismiss-able by click on toast.
toast.error(
"oh, error!",
{ duration: 1000 * 60 }
);
I'd like to add a class to this div through the props/options:
https://github.com/timolins/react-hot-toast/blob/main/src/components/toaster.tsx#L28
So that I can use CSS to catch for example hover and update the CSS for that (in my case, I'm adding a timeout animation that I need to pause for all toasts on hover)
It doesn't look hard to add, so let me know if I can open a PR for this.
Thanks for this great library!
I think this is more like a question. When toast.dismiss
is called, a toast is dismissed after 1s, but if a new toast is created fast enough after dismissed
is called, the toast will be dismissed almost immediately. Should creating a new toast be disabled while the dismissing animation is still in effect?
Hi, I was trying out the plugin and the basic 'Getting Started' code fails to launch the toast for me.
I verified that the component renders properly, but it seems like the toast
function is failing silently. Is there a way to turn on debug/error messages so that I can figure out what's going on?
Here's the full code I used for reference:
import React from 'react';
import toast, { Toaster } from 'react-hot-toast';
const notify = () => toast('Here is your toast.');
const App = () => {
return (
<div>
<button onClick={notify}>Make me a toast</button>
<Toaster />
</div>
);
};
export default App;
The default success / error states are really great! I wonder if there should also be a default warning state (yellow, maybe exclamation mark) too.
This is really cool, ui.dev's newsletter brought me here!
I'm just missing a few features so I'll be making a few issues to keep track of that, starting with this one:
A time-to-live progress bar would make the UX of autodismissal of toasts after a specified duration significantly clearer. The bar should be full when the toast appears and empty out until the specified toast duration passes (when the toast is autodismissed).
Got warning in Chrome: validateDOMNesting(...): <div> cannot appear as a descendant of <p>.
with material-ui's <Alert>
inside toast message (or any other div)
Possible solution: replace 'p'
with 'div'
Hi, thanks for this amazing library.
I have noticed that you expose your internal implementation of dispatch
. Haven't investigated if there is a proper reason for doing this, but from the DX point of view it's terrible because all projects that use Redux with VS Code will import it by mistake when what they want to do is really:
const { dispatch } = props;
or
const dispatch = useDispatch();
I would consider not exporting your lib's internal dispatch to outside users of the lib.
hey guys, I saw the other question about this but it did not help me. I have tried multiple ways to get this to work but cannot seem to make it work.
I tried this:
export const postVersionBulkAction = (args) => {
let url = `${apiBase}/smart-list/version/${args.versionId}/action`
let promise = queue.wrap(async (dispatch) => {
let params = { iabCategoriesActions: args.iabCategoriesActions }
const result = await axios.patch(url, params)
if (result.status === 200) {
}
})
toast.promise(promise, {
loading: 'Saving...',
success: 'saved',
error: 'error'
})
}
but that gives me an error: 'TypeError: promise.then is not a function'
I've also tried this:
export const postVersionBulkAction = (args) => {
let url = `${apiBase}/smart-list/version/${args.versionId}/action`
return queue.wrap(async (dispatch) => {
try {
let params = { iabCategoriesActions: args.iabCategoriesActions }
const result = await axios.patch(url, params)
toast.promise(result, {
loading: 'Saving...',
success: 'saved',
error: 'error'
})
} catch (error) {
alert(error)
}
})
}
but i get 'promise.then is not a function' error on that one too.
I've also tried calling it like this:
const promise = props.postVersionBulkAction(params)
toast.promise(promise, {
loading: 'Saving...',
success: <b>saved!</b>,
error: <b>Could not apply.</b>
})
but that way always fires the success toast even if it fails.
Any idea how i could make this work?
PS. thanks for the awesome product! Other than this problem it has helped me so much, and I have succesfully removed thousands of lines of redux boilerplate because of this library. thanks again
Hii, React Hot Toast team, I see this project to be really awesome and an example of really good work.
Is the React Hot Toast add on Stable or useable for React Native?
Is it possible to avoid rendering the toast completely when the promise being monitored resolves fast?
The current animation is really cool, but doesn't work as well visually when the toast in not centered on the page and has a bouncy feel that may not be suitable to all websites. There should be other options to choose from.
At the moment loading
is required for any toast.promise
calls, but what if someone wants to use toast.promise
but doesn't want to show a toast for the loading state but only for the success or error state?
react-hot-toast/src/core/toast.ts
Lines 65 to 74 in 67bdc5b
Hey! I saw this PR #37 and tried out a duration of Infinity
, but it is just causing the toast to dismiss instantly.
I've put together a CodeSandbox that reproduces the behavior. Any ideas?
https://codesandbox.io/s/pedantic-framework-c3v0x?file=/src/App.js
I need to customize some of the styling for the toast container. I don't see anything in the documentation, but I found containerStyle
in the Toaster component below, however, it doesn't seem to do anything when passing it into the Toaster component.
Is there a reason this is here?
Sometimes we need to show toast until it's dismissed by user or programmatically. E. g. connection lost and notification is shown until it's back online. Or some long or slow process happens.
It is not always possible to use toast.promise
for that. Currently I use very long duration to simulate persistent toast.
Is it possible to add persistent toast, which doesn't have any timers inside them? Then it would possible to do:
const id = toast('No connection.', { persistent: true });
toast('Connected.', { id, persistent: false })
Hi,
First of all, let me say that this library is awesome !
I wanted to use it for a project, however I need a description to the toast, a bit like in tailwind ui, I thought of using the headless mode, but unless wraping your hook to allow for description, do you think of a better way ?
Thanks a lot !
Hey,
Iam trying to use this library inside react-native, however I keep getting
Can't find variable: Document
I have this notifcation component:
import { MaterialIcons } from '@expo/vector-icons'
import React, { useRef } from 'react'
import { useToaster } from 'react-hot-toast'
import { Animated, Text, View } from 'react-native'
const Toast = ({ t, updateHeight, offset }) => {
const fadeAnim = useRef(new Animated.Value(0.5)).current // Initial value for opacity: 0
const posAnim = useRef(new Animated.Value(-80)).current // Initial value for opacity: 0
React.useEffect(() => {
Animated.timing(fadeAnim, {
toValue: t.visible ? 1 : 0,
duration: 300,
useNativeDriver: true,
}).start()
}, [fadeAnim, t.visible])
React.useEffect(() => {
Animated.spring(posAnim, {
toValue: t.visible ? offset : -80,
useNativeDriver: true,
}).start()
}, [posAnim, offset, t.visible])
return (
<Animated.View
pointerEvents='none'
style={{
position: 'absolute',
left: 0,
right: 0,
zIndex: 9999,
alignItems: 'center',
opacity: fadeAnim,
transform: [
{
translateY: posAnim,
},
],
}}>
<View
onLayout={(event) =>
updateHeight(t.id, event.nativeEvent.layout.height)
}
style={{
marginTop: 50,
backgroundColor: t.type === 'success' ? '#4caf50' : '#f44336',
maxWidth: '80%',
borderRadius: 30,
flexDirection: 'row',
alignItems: 'center',
paddingVertical: 8,
paddingHorizontal: 12,
}}
key={t.id}>
<MaterialIcons
name={t.type === 'success' ? 'check-circle-outline' : 'error-outline'}
size={24}
color='white'
/>
<Text
style={{
color: '#fff',
padding: 4,
flex: 1,
textAlign: 'center',
}}>
{t.message}
</Text>
</View>
</Animated.View>
)
}
const Notification = () => {
const { toasts, handlers } = useToaster()
return (
<View
style={{
position: 'absolute',
top: 0,
left: 0,
right: 0,
}}>
{toasts.map((t) => (
<Toast
key={t.id}
t={t}
updateHeight={handlers.updateHeight}
offset={handlers.calculateOffset(t.id, {
reverseOrder: false,
})}
/>
))}
</View>
)
}
export default Notification
and I use that instead of <Toaster />
Apart from that the only imports I do look like this:
import { toast } from 'react-hot-toast'
At the moment the dismiss operation is delayed by 1000ms
and that param is hardcoded into the code. Could it be something useful to configure?
Hey! Awesome library. Something that would be useful for me is an option to set the maximum number of visible toasts, that will automatically dismiss the oldest one when the maximum is reached.
I could do that with useToaster
and a filter but then I would have to replicate everything else <Toaster />
already does, so I would prefer not to.
Is it possible to make toast 'slide' on show and hide instead of bounce effect? For example like in Toastify 'transition' parameter https://fkhadra.github.io/react-toastify/introduction/
I know my question is weird but any possibility of using this library without React?
This issue was original raised by @ambroseus in #5. It would be cool to replace the built-in Message container. It includes styles which are hard to get rid of at the moment.
Ideally you will be a able to provide a custom Component without having to go headless.
Hello.
Can I use toast.promise()
in conjunction with useState
and useContext
?. I'm getting a funny behavior when trying to set state on the success property.
const axiosPromise = publicFetch.post('/auth/login', {
email,
password,
});
toast.promise(axiosPromise, {
loading: 'Authenticating',
success: ({data}) => {
setAuthInfo(data.data) // coming from React Context, here it errors out and says data is undefined.
return '';
},
error: () => 'Error',
});
When trying to set state, data is undefined
, it only happens when using the set state function.
Giving your nice react-hot-toast npm a run in a project I'm working on. We have a simplistic alerts system and just today started looking at libs to upgrade our UI. Trying yours out after reading a blurb from a @tylermcginnis newsletter.
We literally copied this code from your API page and tweaked the duration really long to 30 seconds (30000) while testing some other things but the duration doesn't seem to be honored:
<Toaster
position="top-center"
reverseOrder={false}
toastOptions={{
// Define default options
style: {
margin: '40px',
background: '#363636',
color: '#fff',
zIndex: 1,
},
duration: 5000,
// Default options for specific types
success: {
duration: 3000,
theme: {
primary: 'green',
secondary: 'black',
},
},
}}
/>
We will keep playing around with it and let you know if we determine it is something in our code.
Hi @timolins ๐
I was thinking that the following API would be nice to allow users to default to a certain toast message if none is provided:
// example API
<Toaster types=[{
icon: ErrorIcon,
defaultMessage: 'An error happened'
}]
// in this way one could do the following
toast.error()
// An alternative to this would be to wrap the `toast` object and export it in your application, e.g.
import { toast as toastHander } from 'react-hot-toast'
export const toast = {
...toastHandler,
error: (message, opts) => toastHandler.error(message || 'Your default error message', opts)
}
What do you think?
Has anyone faced an issue when setting a position attribute to Toaster component? Error looks like 'Error: Objects are not valid as a React child (found: object with keys {position}). If you meant to render a collection of children, use an array instead.'
I am currently using the modals provided by react semantic ui
. There is a prop for a modal which makes the blurred. (https://react.semantic-ui.com/modules/modal/).
When I use it, my toasts won't appear, they are "behind" the blurred content. Is there a way to set the z index on the toasts or make them available up front?
I'm wondering what to give notify.promise
when using async/await where I need to access the result. Could you give us an example?
Example:
const onSubmit = async (data) => {
const { key } = await createProject(data)
// Now here comes the question:
notify.promise('What would I possibly use here', {
loading: 'Loading',
success: 'Got the data',
error: 'Error when fetching',
})
push(`/projects/${key}`)
}
Hi, Found this a while back and am interested in using it for my next project. Building an SPA app and I have the Toaster set up like this:
index.js:
import React from 'react';
import { Toaster } from 'react-hot-toast';
const queryClient = new QueryClient()
ReactDOM.render(
<React.StrictMode>
<BrowserRouter>
<Routes>
<Route path='/login' element={<Login />} />
<Route path='/' element={<Dashboard />} />
</Routes>
</BrowserRouter>
<Toaster />
</React.StrictMode>,
document.getElementsById('root')
);
Then in my login component I get an isError bool value back from my query and I have the following in my render component:
return (
<Layout>
{isError && toast(error.toString())}
// render rest of content
)
I keep getting this issue:
index.js:1 Warning: Cannot update a component (Toaster
) while rendering a different component (Login
). To locate the bad setState() call inside Login
, folow the stack trace as described in.
Anyway to get around this?
It'd be greatly useful if toasts had an "X" button or something like that to dismiss them early. That can already be done with the API, but a built-in button would be great.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.