I want to open a modal by click a button which is supposed to export some datas in an excel file.
So there is my code but the modal is still close.
I’m new in react, did I do something wrong ?
Thank’s for your help
function QualityImprovementExcel(props) {
const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8';
const fileExtension = '.xlsx';
const { t } = useTranslation();
const [open, setOpen] = useState(false)
const handleOpen = () => setOpen(true);
const handleClose = () => setOpen(false);
const exportToExcel = () => {
handleOpen()
var excelData = props.formatData(props.excelData);
const ws = XLSX.utils.json_to_sheet(excelData, { header: props.propsExportExcel });
let exportHeader = props.propsHeaderExport.map(array => array.map(item => t(item)));
XLSX.utils.sheet_add_aoa(ws, exportHeader);
const wb = { Sheets: { 'data': ws }, SheetNames: ['data'] };
const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
const data = new Blob([excelBuffer], { type: fileType });
FileSaver.saveAs(data, props.fileName + fileExtension);
handleClose()
}
return (
<div className='quality-improvement-export-div'>
<Button className='quality-improvement-list-filter-buttonExportExcel' onClick={exportToExcel}>
EXCEL
</Button>
<Modal open={open} aria-labelledby="modal-modal-title" aria-describedby="modal-modal-description" >
<Box sx={style}>
<Typography id="modal-modal-title" variant="h6" component="h2">
Text in a modal
</Typography>
<Typography id="modal-modal-description" sx={{ mt: 2 }}>
Duis mollis, est non commodo luctus, nisi erat porttitor ligula.
</Typography>
</Box>
</Modal>
</div>
)
};
2
Answers
It’s still close because handleClose call at the end of exportToExcel function.
The state you are using (
const [open, setOpen] = useState(false);
) is the cause.The on click event currently does the following (all in one go):
since the state is changed without a render in between the open state is never seen.
Not sure what the goal of the modal is if the logic can be done before hand maybe it’s not necessary.
Otherwise you should change your exportToExcel and remove the state changes & add modal interaction to buttons
So something like: