6

Currently, using default alert which is alert(response.data.result). To make my site more beautiful, I want to use Material-ui Alert. https://material-ui.com/components/alert/

My issue is I have no idea on how to call it from const.

Here's my code.

function Test(){
const saveData=async() => {
    await axios.post('/API', passedParams)
    .then(response => {
      if(response.data.success === true)
        {
          alert(response.data.result)
        }
      else
        {
          alert(response.data.result)
          //<Alert severity='error'>{response.data.result}</Alert> tried to use this but nothing displayed
          }
     }).catch(error=>{
        alert(error)
     })

//content of modal
cosnt bodyInsert = (
<div>
    ...fields
    <Button onClick={()=>saveData()}>Save</Button>
</div>
)
return(
<div>
<Modal
   open = {modalInsert}
   onClose = {openCloseModalInsert}>
   {bodyInsert}
</Modal>
</div>
)
}
export default Test;

Hoping for your consideration. thank you.

Rymrk
  • 216
  • 1
  • 3
  • 13
  • You should add your current component into your rendered component and use state to show or hide it. And you can only control this state into true or false to show or hide that component. If you post your full code, then I can help you with code. –  Mar 24 '21 at 12:35
  • Hi @ArtemMedianyk I updated my posted code. Thank you – Rymrk Mar 25 '21 at 02:05

4 Answers4

13
function Test(){
const saveData=async() => {
    const [alert, setAlert] = useState(false);
    const [alertContent, setAlertContent] = useState('');
    await axios.post('/API', passedParams)
    .then(response => {
      if(response.data.success === true)
        {
          setAlertContent(response.data.result);
          setAlert(true);
        }
      else
        {
          setAlertContent(response.data.result);
          setAlert(true);
        }
     }).catch(error=>{
        alert(error)
     })

//content of modal
cosnt bodyInsert = (
<div>
    ...fields
    <Button onClick={()=>saveData()}>Save</Button>
</div>
)
return(
<div>
{alert ? <Alert severity='error'>{alertContent}</Alert> : <></> }
<Modal
   open = {modalInsert}
   onClose = {openCloseModalInsert}>
   {bodyInsert}
</Modal>
</div>
)
}
  • Hi @Artem, thank you! it is now working. I just put the const for alert outside the save function since `alertContent` is undefined inside `return()`. Is there a way to put it over the displayed modal? As of now it displayed beyond the modal specially if error alert. Thank you – Rymrk Mar 25 '21 at 08:15
  • 1
    You will have to pass alertContent to your Modal using props and state. –  Mar 25 '21 at 08:26
2

I think you can not do it that way. Use a state for it.

const [showAlert, setShowAlert] = useState(null);

const saveData=async() => {
    await axios.post('/API', passedParams)
    .then(response => {
      if(response.data.success === true)
        {
          alert(response.data.result)
        }
      else
        {
          alert(response.data.result)
          setShowAlert(response.data.result);
        }
         
     }).catch(error=>{
        alert(error)
     })

// Your return
return showAlert && <Alert severity='error'  onClose={() => setShowAlert(null)} > { showAlert } </Alert>
Vo Quoc Thang
  • 1,338
  • 1
  • 4
  • 5
0

You can use Collapse component collapse doc

const alertComponent = (<Alert severity='error'>{alertContent}</Alert>);

<Collapse in={alert}>{ alertComponent }</Collapse>
Alan Hernandez
  • 309
  • 3
  • 5
0

We can use <Alert> and <Dialog> components to create an alert in the react application

Example:

import React, { useCallback } from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Alert from '@material-ui/lab/Alert'
import IconButton from '@material-ui/core/IconButton'
import CloseIcon from '@material-ui/icons/Close'
import Dialog from '@material-ui/core/Dialog'


const useStyles = makeStyles(theme => ({
    root: {
        '& > * + *': {
            marginTop: theme.spacing(2),
        },
        width: '100%',
    },
}))

export default function TransitionAlerts(props) {
    const classes = useStyles()
    return (
        <div className={classes.root}>
            <Dialog open={props.open}>
                <Alert
                    action={
                        <IconButton
                            aria-label='close'
                            color='inherit'
                            size='small'
                            onClick={
                              useCallback(() => props.closeAlert({msg: '', open: false }))
                            }
                        >
                            <CloseIcon fontSize='inherit' />
                        </IconButton>
                    }
                >
                    {props.msg}
                </Alert>
            </Dialog>
        </div>
    )
}
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133