Pooja Ray Chaudhuri
Pooja Ray Chaudhuri

Reputation: 11

How to make alert on click of button

Is there a way to make Alert on click not using the alert method but Alert tag. Currently I tried using usestate but didn’t work

Upvotes: 0

Views: 1328

Answers (1)

Moss Palmer
Moss Palmer

Reputation: 1854

Hard to know what your problem is without seeing code but this is the general approach to show tag based components. Don't forget to revert the state value on dismissal.

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

return (
 <>
 {showAlert ?
  <Alert {...otherPropsHere} />
 : <View/> }
 <Button title="Press Me" onPress={() => {setShowAlert(true)} />
 </>
)

If the tag has a 'visible' prop then it would be more like this

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

return (
 <>
 <Alert visible={showAlert} {...otherPropsHere} />
 <Button title="Press Me" onPress={() => {setShowAlert(true)} />
 </>
)

If you need multiple alerts you could:

const [showAlertOne, setShowAlertOne ] = useState(false);

return (
 <>
 {showAlertOne ?
  <Alert {...otherPropsHere} />
 : <View/> }
{showAlertTwo ?
  <Alert {...otherPropsHere} />
 : <View/> }
 <Button title="Show Alert One" onPress={() => {setShowAlertOne(true)} />
<Button title="Show Alert Two" onPress={() => {setShowAlertTwo(true)} />
 </>
)

This isn’t the best way to do it but I think this should clear up the concept of what you are trying to do. A better way - if the alerts don’t show at the same time - is to have a single state object in which you store which alert you want to show. These could be an ENUM too to add a little safety.

This is the (partially) typed example with an enum and a wrapped component.

const myApp = () => {

  enum AlertType = { One, Two, Three }
  const [visibleAlert, setVisibleAlert ] = useState<AlertType | null>(null);

  const VisibleAlert = (alertType:AlertType) => {
    switch (visibleAlert) {
      case AlertType.One:
        return <Alert {otherPropsHere} />
      break;
      case AlertType.One:
        return <Alert {otherPropsHere} />
      break;
      default:
        return <View/>
      break;
    }
  }>

  return (
   <>
     <VisibleAlert alertType={visibleAlert} />
     <Button title="Show Alert One" onPress={() => {setVisibleAlert(AlertType.One)} />
     <Button title="Show Alert Two" onPress={() => {setVisibleAlert(AlertType.Two)} />
   </>
  )
}

Wrapping the modal in a component with its own state might be a good approach but let’s see what your issue is for sure first.

Upvotes: 1

Related Questions