Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
)
}
like image 596
Fatih mzm Avatar asked Nov 26 '25 06:11

Fatih mzm


1 Answers

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
like image 158
sbodi Avatar answered Nov 27 '25 20:11

sbodi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!