import React, { useEffect } from 'react';
import { createRoot } from 'react-dom/client';
import { ThemeProvider, createTheme } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import GlobalStyles from '@mui/material/GlobalStyles';
import Info from '../../info'
const theme = createTheme({
palette: {
primary: {
main: '#1976d2',
},
secondary: {
main: '#42a5f5',
contrastText: '#fff',
},
},
});
const globalStyles = {
td: {
whiteSpace: 'nowrap',
textOverflow: 'ellipsis',
overflow: 'hidden',
maxWidth: 200,
},
'.dialog-content': {
fontSize: '0.9rem',
},
};
const DataWindow = ({ data, context, onClose }) => {
useEffect(() => {
const path = `/info/${context}/info?id=${data.id}`;
const windowName = `${context}: ${data.name}`;
const newWindow = window.open(path, windowName, "width=800,height=400");
if (newWindow) {
newWindow.document.title = `${context}: ${data.name}`;
newWindow.document.body.style.overflow = 'auto';
const container = newWindow.document.createElement('div');
newWindow.document.body.appendChild(container);
const handleUnload = () => {
onClose();
newWindow.close();
};
newWindow.addEventListener('beforeunload', handleUnload);
const root = createRoot(container);
let isUnmounted = false;
if (!isUnmounted) {
root.render(
<ThemeProvider theme={theme}>
<CssBaseline />
<GlobalStyles styles={globalStyles} />
<Info rcId={data.id} />
</ThemeProvider>
);
}
return () => {
isUnmounted = true;
newWindow.removeEventListener('beforeunload', handleUnload);
};
}
}, [data, context, onClose]);
return null;
};
export default DataWindow;
I am opening the window and it opens properly, and it gets redirected to the path which renders all the information inside the window. Now in my parent file,
const handleInfoClick = (rowData) => {
console.log("OPEN WINDOW");
setSelectedRowData(rowData);
setIsPopupOpen(true);
};
const handleClosePopup = () => {
console.log("CLOSE WINDOW");
setIsPopupOpen(false);
};
<DataWindow
data={selectedRowData}
context="rc"
onClose={handleClosePopup}
/>
When I open the window OPEN WINDOW
appears in the console, when I close the window CLOSE WINDOW
does not appear. If I remove the path and keep it empty.
const newWindow = window.open('', windowName, "width=800,height=400");
Then when I repeat the opening and closing process CLOSE WINDOW
appears on the console.
I am confused why is the handleUnload being called when there is no path and not being called when there is a path.
Chaitanya Yeole is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.