React Local Toast is a lightweight, flexible library for displaying toast notifications in React applications. It provides a simple API for showing temporary messages that appear and disappear automatically, perfect for user feedback, success messages, and error alerts. This guide walks through setting up and creating toast notifications using React Local Toast with React, from installation to a working implementation. This is part 34 of a series on using React Local Toast with React.
Prerequisites
Before you begin, make sure you have:
- Node.js version 14.0 or higher installed
- npm, yarn, or pnpm package manager
- A React project (version 16.8 or higher) or create-react-app setup
- Basic knowledge of React hooks (useState)
- Familiarity with JavaScript/TypeScript
Installation
Install React Local Toast using your preferred package manager:
npm install react-local-toast
Or with yarn:
yarn add react-local-toast
Or with pnpm:
pnpm add react-local-toast
After installation, your package.json should include:
{
"dependencies": {
"react-local-toast": "^4.0.0",
"react": "^18.0.0",
"react-dom": "^18.0.0"
}
}
Project Setup
Set up the toast provider in your main entry file:
// src/index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { LocalToastProvider } from 'react-local-toast';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<LocalToastProvider>
<App />
</LocalToastProvider>
</React.StrictMode>
);
First Example / Basic Usage
Let's create a simple toast notification component. Create a new file src/ToastExample.jsx:
// src/ToastExample.jsx
import React from 'react';
import { useLocalToast } from 'react-local-toast';
function ToastExample() {
const toast = useLocalToast();
const showSuccessToast = () => {
toast.success('Operation completed successfully!');
};
const showErrorToast = () => {
toast.error('Something went wrong!');
};
const showInfoToast = () => {
toast.info('Here is some information.');
};
const showWarningToast = () => {
toast.warning('Please review your input.');
};
return (
<div style={{ padding: '20px' }}>
<h2>Toast Notification Examples</h2>
<div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
<button onClick={showSuccessToast}>Success Toast</button>
<button onClick={showErrorToast}>Error Toast</button>
<button onClick={showInfoToast}>Info Toast</button>
<button onClick={showWarningToast}>Warning Toast</button>
</div>
</div>
);
}
export default ToastExample;
Update your App.jsx:
// src/App.jsx
import React from 'react';
import ToastExample from './ToastExample';
import './App.css';
function App() {
return (
<div className="App">
<ToastExample />
</div>
);
}
export default App;
This creates basic toast notifications that appear when you click the buttons and automatically disappear after a few seconds.
Understanding the Basics
React Local Toast uses a hook-based API where:
- useLocalToast: Hook that provides toast functions
- toast.success: Show a success toast
- toast.error: Show an error toast
- toast.info: Show an info toast
- toast.warning: Show a warning toast
- toast.show: Show a custom toast with options
Key concepts:
-
Provider Component:
LocalToastProvidermust wrap your app -
Hook Usage: Use
useLocalToasthook in components to access toast functions - Automatic Dismissal: Toasts automatically disappear after a set duration
- Positioning: Toasts can be positioned in different corners
- Customization: Toast appearance and behavior can be customized
Here's an example with custom options:
// src/CustomToastExample.jsx
import React from 'react';
import { useLocalToast } from 'react-local-toast';
function CustomToastExample() {
const toast = useLocalToast();
const showCustomToast = () => {
toast.show('Custom toast message', {
type: 'success',
duration: 5000,
position: 'top-right'
});
};
const showLongToast = () => {
toast.success('This is a longer toast message that will stay visible for 10 seconds', {
duration: 10000
});
};
const showBottomToast = () => {
toast.info('This toast appears at the bottom', {
position: 'bottom-center'
});
};
return (
<div style={{ padding: '20px' }}>
<h2>Custom Toast Examples</h2>
<div style={{ display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
<button onClick={showCustomToast}>Custom Toast</button>
<button onClick={showLongToast}>Long Duration Toast</button>
<button onClick={showBottomToast}>Bottom Position Toast</button>
</div>
</div>
);
}
export default CustomToastExample;
Practical Example / Building Something Real
Let's build a form component with toast notifications for user feedback:
// src/FormWithToast.jsx
import React, { useState } from 'react';
import { useLocalToast } from 'react-local-toast';
function FormWithToast() {
const toast = useLocalToast();
const [formData, setFormData] = useState({
name: '',
email: '',
message: ''
});
const [errors, setErrors] = useState({});
const handleInputChange = (e) => {
const { name, value } = e.target;
setFormData(prev => ({ ...prev, [name]: value }));
if (errors[name]) {
setErrors(prev => ({ ...prev, [name]: '' }));
}
};
const validateForm = () => {
const newErrors = {};
if (!formData.name.trim()) {
newErrors.name = 'Name is required';
}
if (!formData.email.trim()) {
newErrors.email = 'Email is required';
} else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(formData.email)) {
newErrors.email = 'Invalid email format';
}
if (!formData.message.trim()) {
newErrors.message = 'Message is required';
}
setErrors(newErrors);
return Object.keys(newErrors).length === 0;
};
const handleSubmit = async (e) => {
e.preventDefault();
if (!validateForm()) {
toast.error('Please fill in all fields correctly.');
return;
}
// Show loading toast
toast.info('Submitting form...', { duration: 2000 });
try {
// Simulate API call
await new Promise(resolve => setTimeout(resolve, 2000));
toast.success('Form submitted successfully!', {
duration: 3000
});
// Reset form
setFormData({ name: '', email: '', message: '' });
setErrors({});
} catch (error) {
toast.error('Failed to submit form. Please try again.', {
duration: 4000
});
}
};
return (
<div style={{ padding: '20px', maxWidth: '500px', margin: '0 auto' }}>
<h2>Contact Form with Toast Notifications</h2>
<form onSubmit={handleSubmit}>
<div style={{ marginBottom: '16px' }}>
<label
htmlFor="name"
style={{
display: 'block',
marginBottom: '4px',
fontWeight: '500'
}}
>
Name *
</label>
<input
type="text"
id="name"
name="name"
value={formData.name}
onChange={handleInputChange}
style={{
width: '100%',
padding: '8px',
border: `1px solid ${errors.name ? '#dc3545' : '#ddd'}`,
borderRadius: '4px',
fontSize: '14px',
boxSizing: 'border-box'
}}
/>
{errors.name && (
<div
style={{
color: '#dc3545',
fontSize: '12px',
marginTop: '4px'
}}
>
{errors.name}
</div>
)}
</div>
<div style={{ marginBottom: '16px' }}>
<label
htmlFor="email"
style={{
display: 'block',
marginBottom: '4px',
fontWeight: '500'
}}
>
Email *
</label>
<input
type="email"
id="email"
name="email"
value={formData.email}
onChange={handleInputChange}
style={{
width: '100%',
padding: '8px',
border: `1px solid ${errors.email ? '#dc3545' : '#ddd'}`,
borderRadius: '4px',
fontSize: '14px',
boxSizing: 'border-box'
}}
/>
{errors.email && (
<div
style={{
color: '#dc3545',
fontSize: '12px',
marginTop: '4px'
}}
>
{errors.email}
</div>
)}
</div>
<div style={{ marginBottom: '16px' }}>
<label
htmlFor="message"
style={{
display: 'block',
marginBottom: '4px',
fontWeight: '500'
}}
>
Message *
</label>
<textarea
id="message"
name="message"
value={formData.message}
onChange={handleInputChange}
rows={4}
style={{
width: '100%',
padding: '8px',
border: `1px solid ${errors.message ? '#dc3545' : '#ddd'}`,
borderRadius: '4px',
fontSize: '14px',
resize: 'vertical',
fontFamily: 'inherit',
boxSizing: 'border-box'
}}
/>
{errors.message && (
<div
style={{
color: '#dc3545',
fontSize: '12px',
marginTop: '4px'
}}
>
{errors.message}
</div>
)}
</div>
<button
type="submit"
style={{
width: '100%',
padding: '10px',
backgroundColor: '#007bff',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer',
fontSize: '16px'
}}
>
Submit
</button>
</form>
</div>
);
}
export default FormWithToast;
Now create a custom hook for reusable toast notifications:
// src/hooks/useToastNotifications.js
import { useCallback } from 'react';
import { useLocalToast } from 'react-local-toast';
export const useToastNotifications = () => {
const toast = useLocalToast();
const showSuccess = useCallback((message, options = {}) => {
toast.success(message, {
duration: 3000,
...options
});
}, [toast]);
const showError = useCallback((message, options = {}) => {
toast.error(message, {
duration: 5000,
...options
});
}, [toast]);
const showInfo = useCallback((message, options = {}) => {
toast.info(message, {
duration: 3000,
...options
});
}, [toast]);
const showWarning = useCallback((message, options = {}) => {
toast.warning(message, {
duration: 4000,
...options
});
}, [toast]);
return {
showSuccess,
showError,
showInfo,
showWarning
};
};
Update your App.jsx:
// src/App.jsx
import React from 'react';
import FormWithToast from './FormWithToast';
import './App.css';
function App() {
return (
<div className="App">
<FormWithToast />
</div>
);
}
export default App;
This example demonstrates:
- Form validation with toast feedback
- Success and error notifications
- Loading state notifications
- Custom toast durations
- Integration with form submission
Common Issues / Troubleshooting
Toasts not displaying: Ensure
LocalToastProviderwraps your app at the root level. The provider must be a parent of components usinguseLocalToast.Hook not working: Make sure you're calling
useLocalToastinside a component that's a child ofLocalToastProvider. The hook cannot be used outside the provider context.Toasts appearing in wrong position: Use the
positionoption when calling toast functions. Available positions include 'top-left', 'top-right', 'top-center', 'bottom-left', 'bottom-right', 'bottom-center'.Toasts not auto-dismissing: Check the
durationoption. Set a duration in milliseconds (e.g., 3000 for 3 seconds). If duration is 0 or not set, toasts may not auto-dismiss.Multiple toasts stacking: React Local Toast handles multiple toasts automatically. They will stack based on the position setting.
Styling issues: React Local Toast comes with default styles. You can customize the appearance by passing style options or using CSS to override default styles.
Next Steps
Now that you have a basic understanding of React Local Toast:
- Learn about advanced customization options
- Explore different toast positions and animations
- Implement toast queues and limits
- Add custom toast components
- Integrate with React Context for global toast management
- Learn about other toast libraries (react-toastify, notistack)
- Check the official repository: https://github.com/OlegWock/react-local-toast
- Look for part 35 of this series for more advanced topics
Summary
You've successfully set up React Local Toast in your React application and created toast notifications for user feedback. React Local Toast provides a simple, lightweight solution for displaying temporary messages with minimal configuration.
SEO Keywords
react-local-toast
React toast notifications
react-local-toast tutorial
React notification library
react-local-toast installation
React toast messages
react-local-toast example
React alert notifications
react-local-toast setup
React toast hooks
react-local-toast customization
React notification system
react-local-toast provider
React toast library
react-local-toast getting started
Top comments (0)