How can I display messages in component with react-alert?

Viewed 14805

I'm using reactjs. I want to show alert in component with react-alert component. https://www.npmjs.com/package/react-alert I wrap the index.js file as given at.

but when I try to use alert.show ("sdfsdfsdfsf") in the form, I get the following error.

do I show a message in a form?

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App/App';

import { transitions, positions, Provider as AlertProvider } from 'react-alert'
import AlertTemplate from 'react-alert-template-basic'

import { Provider } from 'react-redux';

const options = {
    // you can also just use 'bottom center'
    position: positions.BOTTOM_CENTER,
    timeout: 5000,
    offset: '30px',
    // you can also just use 'scale'
    transition: transitions.SCALE
};
ReactDOM.render(
    <Provider store={store}>
        <AlertProvider template={AlertTemplate} {...options}>
            <App/>
        </AlertProvider>
    </Provider>,
document.getElementById('root'));

myForm.js

import { useAlert } from "react-alert";
const alert = useAlert();
class myForm extends Component {
  constructor(props) {
    super(props);
.........

render() {
return(
<div> alert.show("Alert test") </div>
)
}
2 Answers

You are using:

render(){                                                            
  return(
  <div> alert.show("Alert test") </div>                                    
   )
}

But you need to use an event to display that alert.

Use this instead:

render(){ 
  return(                                                                
    <div                                                             
      onClick={() => 
        {alert.show('Alert test')}
      }
    />
  )
}

You cannot call a function / method inside the render method unless it is wrapped in curly braces. Curly braces are required in jsx to let the parser know that you want to run some javascript code.

Try the following:

render() {
   return (
     <div>{alert.show("Alert test")}</div>
   );
}

The react-alert package on npm also has a nice example when using an onClick handler https://www.npmjs.com/package/react-alert

const App = () => {
  const alert = useAlert()

  return (
    <button
      onClick={() => {
        alert.show('Oh look, an alert!')
      }}
    >
      Show Alert
    </button>
  )
}

export default App
Related