Giter Site home page Giter Site logo

sweetalert-react's Introduction

sweetalert-react

NPM version Dependency Status

Declarative SweetAlert in React

Introduction

sweetalert-react is a wrapped sweetalert implementation with declarative React style component APIs. There is a show prop available for toggling alert component's visibility. And onConfirm, onCancel, onClose, onEscapeKey, onOutsideClick props allow you have a fine grained control over alert component events.

Install

$ npm install sweetalert-react

Usage

import React, { Component } from 'react';
import SweetAlert from 'sweetalert-react';

// ...

render() {
  return (
    <div>
      <button onClick={() => this.setState({ show: true })}>Alert</button>
      <SweetAlert
        show={this.state.show}
        title="Demo"
        text="SweetAlert in React"
        onConfirm={() => this.setState({ show: false })}
      />
    </div>
  );
}

You should import sweetalert.css from CDN, file, node_modules(sweetalert/dist/sweetalert.css) or wherever method to include this CSS file.

Checkout the full examples here.

Removed Options

  • timer: You should use setTimeout and pass show as false.
  • closeOnConfirm: You should pass show as false via onConfirm.
  • closeOnCancel: You should pass show as false via onCancel.
  • allowEscapeKey: You should pass show as false via onEscapeKey.
  • allowOutsideClick: You should pass show as false via onOutsideClick.

All other options can be passed as props, see them in Configuare Section in sweetalert document

FAQ

Q: My alert didn't close when 'go back' or 'go forward' in browser

You can listen to history changes and set show: false when it is mounted. See the full example here.

Q: Can I use react component to render HTML as the alert body?

Sure, you can achieve this with ReactDOMServer.renderToStaticMarkup:

import { renderToStaticMarkup } from 'react-dom/server';

<SweetAlert
  show={this.state.show}
  title="Demo"
  html
  text={renderToStaticMarkup(<HelloWorld />)}
  onConfirm={() => this.setState({ show: false })}
/>

See the full example here. Thanks @ArkadyB for discovering the approach in issue #53.

Relevant Projects

License

MIT ยฉ C.T. Lin

sweetalert-react's People

Contributors

chentsulin avatar greenkeeperio-bot avatar konekoya avatar matthewchang avatar thiagovice avatar tume avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

sweetalert-react's Issues

Problem with z-index

Hello, I'm having a problem where I'm trying to use a select input from material-ui and the values of the select are being shown behind the Sweet Alert modal, I tried to modify the alert z-index but I'm having troubles with the dark overlay that the alert creates, since it doesn't have any classes.

Maybe someone experienced the same issue and could share a solution/work-around?

Cannot read property 'parentNode' of null

errors with Cannot read property 'parentNode' of null

child component: onConfirm={this.props.confirmAction}

parent component: confirmAction={this.confirm.bind(this)}

function:

  confirm() {
    this.setState({
      saving: true,
      confirm: true,
    }, () => {
      this.save()
    })
  }

really don't understand the strange behaviour, when I remove setState from function confirm of parrent component, it works

chained sweetalert call controlled by redux store

  saBuilder(){
    const { // Boolean hooks as "semaphore" to display/hide the defined sw
      showAlert_confirm, 
      showAlert_cancel, 
      setting_succeed, 
      setting_failed, 
      tip_ip_set,
    } = this.props;

    const getS = () => { // getSentence for a specified alert (what kind of error is this)
      return this.props.ipChanged ? "S_XS" : "S_SX";
    }

    const t = [ // Array for different event alertion contents
      [ showAlert_confirm, "S_FY", "S_FC", true,  "warning", this.alert_confirm_confirm, this.alert_confirm_canceled ], // Confirm alert
      [ showAlert_cancel,  "S_CC", "S_CT", true,  "warning", this.alert_cancel_confirm,  this.alert_cancel_canceled  ], // Cancel alert
      [ setting_succeed,   "S_SS", getS(), false, "success", this.alert_OK_suc,  this.alert_OK_suc  ], // setting succeed
      [ setting_failed,    "S_SF", "S_SA", false, "error",   this.alert_OK_fai,  this.alert_OK_fai  ], // setting failed
    ];
    return t.map(
      (e, i) => <SweetAlert 
        show={e[0]}
        key ={e[1]}
        title={trans(e[1])}
        text ={trans(e[2])}
        type ={e[4]}
        showCancelButton = {e[3]}
        confirmButtonColor="#DD6B55"
        onConfirm=   { () => e[5]() }
        onCancel=    { () => e[6]() }
        onEscapeKey= { () => e[6]() }
        animation = {false}
    />);
  }

My questions is:
The code above works OK when these alerts a in the same React class. But if I'd like to trigger different sweetalert that difined in different React classes through these "Semaphores" that stored in the redux stores. It work not garantee anymore.
I've tracked the lifecyle functions call from these two modules. I find out that, I did turn off one sweetalert semaphore at first (in one module) and then turn on another for the other sweetalert that should be turned on in another module. But the second is just not shown up. In the Dom, it tells me that the second one should be shown, But if I change the state or props of the second react class. I got the alert...
My suspections:
The sweetalert library will not fast enough to mount / unmount its module in the DOM and React-Dom dose not tracking the change state of the sweetalert module. If this is the deal. That means we need a callback function from this library. Did we have one?

Link available in sweetalert-react

Hello!

I really like your work with sweetalert-react, but I wonder if I can use Link from react-router-dom?

Because when I log the context all I get is undefined.

Thanks!

onOutsideClick get fired when body of popup get clicked (when lazy created)

Hi,
found an issue with the onOutsideClick handler. It get fired even if I click input field inside the popup.
(Note that this is not duplicate with previous reported issue)

If I render SweetAlert but don't show it yet and later on change the show:true, then this invalid behavior happens. If I have show:true on initial render time, then everything works.

Looks like that if it's show:false, when registerOutsideClickHandler get executed, it document.getElementsByClassName('sweet-alert') returns null (of course because the popup is not created.

Found out that if I move the registerOutsideClickHandler from componentDidMount after the place in setupWithProps where it creates the popup then it starts to work.

Change button names

Hi chentsulin,

Big Thanks again for your efforts to bring out such a poetry touch of the very popular Sweet-Alert to the React Planet! ๐ŸŒฑ ๐ŸŒ Since I'm using React & Sweetalert for my production repos. I've implemented this repo as connector between this two libraries.

No Big Deal, just drop by to thank you and ask you this small question:

How to change the name of the button?

I've checked out your sweetalert-react/src/SweetalertAlert.js wrapper. Because of the lack of expirences, I believe I saw nothing... ๐Ÿ™ˆ It's not that important really. But it would be a nice to have Know-How

Feature suggestion: `show` prop removal

Is there a reason for show prop? I mean, couldn't the mount and unmount of the component serve as show toggle? Besides the fact it's easier to manage (no more listen to history or anything like that) what is the point of having the Swal mounted if not showing it? I can't think of any single good reason by now

showInputError

Is there any way to use showInputError

Like this example

swal({
  title: "An input!",
  text: "Write something interesting:",
  type: "input",
  showCancelButton: true,
  closeOnConfirm: false,
  animation: "slide-from-top",
  inputPlaceholder: "Write something"
},
function(inputValue){
  if (inputValue === false) return false;
  
  if (inputValue === "") {
    swal.showInputError("You need to write something!");
    return false
  }
  
  swal("Nice!", "You wrote: " + inputValue, "success");
});

Should have and props.children and place like body of sweet alert

I have a case,need to input and Component with handle into sweet alert,but for now can not do this.

renderToStaticMarkup(<HelloWorld />)

just render html not javascript inside,
So Can we do like this:

<SweetAlert>
    <ChildComponent />
</SweetAlert>

we can place ChildComponent like body of SweetAlert?
Thanks

Second popup Cancel button

...
onConfirm={(inputValue) => {
	if (playlistNames.indexOf(inputValue) != -1) {
	swal({
			title: "Duplicate",
			text: "A Playlist with that name already exists",
			type: "info",
			showCancelButton: true,
			confirmButtonColor: "#DD6B55",
			confirmButtonText: "Yes, create it!",
			closeOnConfirm: false,
			closeOnCancel: false
		},
		function(isConfirm){ //Only Confirm button gets here
			console.log(isConfirm); //Never false
			if(isConfirm) {
			  this.setState({showNewPlaylistPrompt: false});
			  this.props.newPlaylist(inputValue);
			}
			else {
			  this.setState({showNewPlaylistPrompt: false});
			}
		  }.bind(this));
	  return;
	}
  }}

Module not found

Excuse me, I have something problem:

I clone this repo and running npm install,
and switch to example/simple this example, and I running npm install.

after running npm install, I execute npm start, have something error:
Module not found: Error Cannot resolve module 'react'

then, I open package.json add react into dependencies,
save and run npm start it can work.

Why have this error message? ๐Ÿ˜ง
Thank you.

Publish v0.4.10

Can you please publish 0.4.10 to npm as you updated the repo but never published the version.

Render custom coponent that operates with state

SweetAlert code:

<SweetAlert
      show={cartOpened}
      title="Cart"
      html
      text={renderToStaticMarkup(<Cart />)}
      onConfirm={showCart(false)}
    />

Cart is a complex component, that uses redux. I`m using recompose too.

Got a following error:
Uncaught Error: Could not find "store" in either the context or props of "Connect(withState(withHandlers(Cart)))". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(withState(withHandlers(Cart)))".

What can I do?

React v16.9.0 warning componentWillReceiveProps has been renamed

Using react v16.9.0 I am getting a warning in console when I am importing the library.
The warning reads as follows.

backend.js:1 Warning: componentWillReceiveProps has been renamed, and is not recommended for use. See https://fb.me/react-async-component-lifecycle-hooks for details.

* Move data fetching code or side effects to componentDidUpdate.
* If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state
* Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.

Please update the following components: SweetAlert

simply things be made complicated

Removed Options

timer: You should use setTimeout and pass show as false.
closeOnConfirm: You should pass show as false via onConfirm.
closeOnCancel: You should pass show as false via onCancel.
allowEscapeKey: You should pass show as false via onEscapeKey.
allowOutsideClick: You should pass show as false via onOutsideClick.

not a good idea, an extra stateful node must be create for using this sweetalert thing.

Umbrella 1.0

  • Make sure onConfirm, onCancel, onClose, onEscapeKey and onOutsideClick is hot-reloadable (#5)
  • pull request to sweetalert to have a commonjs entry point (t4t5/sweetalert#440)
  • more tests
  • gh-pages
  • Deal with more than 2 SweetAlert component (Define behavior)

How to render text with html element

I want to render Sweetalert with text having HTML elements, How can I fo that? Right now I am rendering the Sweetalert like this

<SweetAlert
  show={showConfirm}
  title={title}
  text="Are you sure you want to remove task <b>Rolling</b>?"
  showCancelButton
  confirmButtonText="Confirm"
  customClass="confirm-modal confirm-delete-modal"
  onConfirm={this.handleConfirmClick}
  onCancel={this.hideConfirm}
/>

So here, instead of showing Rolling in bold letters it is rendering text as Are you sure you want to remove task <b>Rolling</b>?

ReferenceError: window is not defined

When starting webpack to run our reactjs project w/ your sweetalert-react library (to get those nice alerts), we can't get it to work for the same reason why we can't get the original sweetalert library to work:

/vagrant/app/node_modules/sweetalert/lib/modules/utils.js:37
  if (window.console) {
      ^

ReferenceError: window is not defined
    at Object.logStr (/vagrant/app/node_modules/sweetalert/lib/modules/utils.js:37:7)
    at Object.<anonymous> (/vagrant/app/node_modules/sweetalert/lib/sweetalert.js:301:48)
    at Module._compile (module.js:413:34)
    at Module._extensions..js (module.js:422:10)
    at Object.require.extensions.(anonymous function) [as .js] (/vagrant/app/node_modules/babel-core/lib/api/register/node.js:214:7)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Module.require (module.js:367:17)
    at require (internal/module.js:16:19)
    at Object.<anonymous> (/vagrant/app/node_modules/sweetalert-react/lib/SweetAlert.js:17:19)

window is called in the original sweetalert file, and calling an import of the sweetalert-react library calls an import on 'sweetalert', which fails the start of the webpack build. How were you able to get past this issue?

window is still undefined in serverside rendering

I use parcel-bundler instead of webpack. I've tried to do so:

import swal from 'sweetalert';
import SweetAlert from 'sweetalert-react'; // eslint-disable-line import/no-extraneous-dependencies
import 'sweetalert/dist/sweetalert.css';
 componentDidMount(){
        if (typeof(window) == 'undefined') global.window = new Object();    
  }
    render(){
       return(
            <div className="ro">
            {
                typeof window !== 'undefined' && (
                <SweetAlert
                    show={this.state.show}
                    title="Demo"     
                /> );
    }

so in this case I want to render sweet alert only in browser. The problem is this error:

node_modules/sweetalert/lib/modules/utils.js:37
  if (window.console) {
  ^

ReferenceError: window is not defined

doesn't global.window avoid the issue?
Thanks

Missing type property

I don't see the type property as used in vinilla sweetalert. Whats the status on this?

Thanks!

Dismount when changing url

When changing the url (clicking browsers back button), the component is unmounted, but still visible. Is it possible to hide then also the SweetAlert dialog? I tried it with forceUpdate(), but the rendering method is not called anymore after componentWillUnmount().

Thank you

Possible to do the custom callback from sweet alert?

The example from http://t4t5.github.io/sweetalert/, specifically:

A warning message, with a function attached to the "Confirm"-button...

swal({   
  title: "Are you sure?",   
  text: "You will not be able to recover this imaginary file!",   
  type: "warning",   
  showCancelButton: true,  
  confirmButtonColor: "#DD6B55",   
  confirmButtonText: "Yes, delete it!",   
  closeOnConfirm: false 
}, 
function(){   
  swal("Deleted!", "Your imaginary file has been deleted.", "success"); 
}
);

Hack for better confirm & close api

  • Maybe add show props
  • use callback manually handle alert lifecycle
  • remove timer attr
  • closeOnConfirm, closeOnCancel should be removed
  • add onConfirm, onCancel

input doesn't working in render html for popup body?

i try set a popup with 2 fields, i am try as a component but it just show the labels, and doesn't show the fields

class App extends Component {
      constructor(props) {
        super(props);
        this.state = {
          show: false,
        };
      }
      render() {
        return (
          <div className="App">
          <SweetAlert
              show='true'
              title="Demo"
              html
              text={renderToStaticMarkup(<HelloWorld />)}
              onConfirm={() => this.setState({ show: false })}
            />
          </div>
        );
      }
    }

and it is my component HelloWorld,

 import React from 'react';
const HelloWorld = () =>
 <div>
     <div class="form-group">
         <label for="exampleInputEmail1">Email address</label>
         <input type="email" class="form-control" id="exampleInputEmail1" aria- describedby="emailHelp" placeholder="Enter email" />
     </div>
     <div class="form-group">
         <label for="exampleInputPassword1">Password</label>
         <input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password" />
     </div>
 </div>

export default HelloWorld;

Differentiate between onConfirm and onClose calls

I am using SweetAlert2 to alert the user. When I click on the confirm button the behavior is as expected, delete keyword call is made.

render: function() {
return(
<SweetAlert show={this.state.show} title="Context Processor"
                 text="Keyword deletion cannot be undone. Do you still want to continue?"
                onConfirm={this.deleteKeyword}
                showCloseButton={true}
                heightAuto={false}>
                </SweetAlert>
)},

deleteKeyword: function() {
        this.setState({show: false});
        this.props.deleteKeyword(this.state.keyword);
    },

However, when I simply close the alert box call is made then again! I went through the various options provided by the library - https://github.com/kessejones/react-sweetalert2/blob/master/src/ReactSweetAlert2.js but I couldn't find any of interest. Also, added showCloseButton parameter but again when I click on it the delete keyword call is made.

The call is always made to the method passed in onClose and then the method passed in onConfirm is executed. How can I execute different methods for confirming and canceling/closing?

SweetAlert V2

There seems to be a major revision, is this repo going to keep up?

Sweetalert displays 'Not valid!'

<SweetAlert
  show={this.state.show}
  title="Demo"
  text="SweetAlert in React"
  onConfirm={() => this.setState({ show: false })}
/>

Displays

image

Tried and tested with all the different examples found in /examples.
Same result across the board.

Doing npm install sweetalert-react

setState deleting Input value

Let's say I have a SweetAlert such as this

<SweetAlert
  show={this.state.show}
  title="Name"
  text="What is your name"
  type='input'
/>

and somewhere else I have a setState happening

setTimeout(() => {
  this.setState({fus: 'ro-dah'});
}, 5000)

Once the setState happens the inputed value is deleted

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.