I’m working on a .NET Core MVC project with Razor Pages and trying to integrate Sonner (a React-based toast notification library) into my application. I have a few questions and issues with this integration.
Current Setup
I created a new directory within wwwroot to manage my React setup. I initialized this directory with npm and installed react, react-dom, and sonner:
npm init -y
npm install react react-dom sonner
I developed a React component (ToastComponent) that includes a button for triggering a toast notification:
import React from 'react';
import { Toaster, toast } from 'sonner';
function ToastComponent() {
const showToast = () => {
toast('Knock knock, A toast!');
};
return (
<div>
<Toaster />
<button onClick={showToast}>Show Toast</button>
</div>
);
}
export default ToastComponent;
To bundle the React component, I set up Webpack and Babel. I installed the necessary packages with:
npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env @babel/preset-react
web.config.js
const path = require('path');
module.exports = {
entry: './wwwroot/react/ToastComponent.jsx',
output: {
path: path.resolve(__dirname, 'wwwroot/dist'),
filename: 'bundle.js',
},
module: {
rules: [
{
test: /.(js|jsx)$/,
exclude: /node_modules/,
use: 'babel-loader',
},
],
},
resolve: {
extensions: ['.js', '.jsx'],
},
};
.babelrc
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
And to pack
npx webpack
I included the bundled JavaScript file in my Razor Page and attempted to render the React component:
@page
@model ...
@{
ViewData["Title"] = "React Toast Example";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>@ViewData["Title"]</title>
</head>
<body>
<div id="react-toast"></div>
<script src="~/dist/bundle.js"></script>
<script>
ReactDOM.render(React.createElement(ToastComponent), document.getElementById('react-toast'));
</script>
</body>
</html>
Issue Encountered
When I attempt to use the toast notification, I encounter the following error:
Uncaught ReferenceError: toast is not defined
This error indicates that the toast function, which is part of the Sonner library, is not recognized in the context where it’s being called.
My question is, is it feasible to use a React-based library like Sonner for toast notifications within a .NET Core MVC Razor Page setup? and if not are there alternative approaches or best practices for integrating React components and libraries into a Razor Pages application effectively?
Any guidance or suggestions to help resolve these issues would be greatly appreciated! 😀