最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to display a modal dialog box in ReactJS? - Stack Overflow

programmeradmin2浏览0评论

I'm new to JavaScript and ReactJS.

I have an application, in which the user enters his or her e-mail address. Then I try to create the user record. If something goes wrong, I want to display a modal window with the error message.

handleSubmit(evt) {
  evt.preventDefault()
  var email = this.state.email
  var userCreationResult = this.createUser(email)
  if (!userCreationResult.success) {
    // The modal window should be displayed here
    return
  }
}

react-bootstrap has a ponent for modal windows. I created a class based on it:

import React, { Component, Modal } from 'react';

class ModalMessageBox extends Component {
  constructor() {
    super()
  }
  render() {
    return (
      <div>
        <Modal>
          <Modal.Header closeButton>
            <Modal.Title>Modal heading</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <h4>An error occured</h4>
            <p>Test error message.</p>
          </Modal.Body>
        </Modal>
      </div>
    )
  }
}

export default ModalMessageBox;

When the user creation error occurs, I try to display it using this code:

handleSubmit(evt) {
  evt.preventDefault()
  var email = this.state.email
  var userCreationResult = this.createUser(email)
  if (!userCreationResult.success) {
    var dialog = new ModalMessageBox();
    ReactDOM.render(dialog, document.getElementById('root'));

This doesn't work -- I get the error ReactDOM.render(): Invalid ponent element..

What is the right way to display a modal dialog in React?

Update 1 (27.07.2017 15:27 MSK):

Class, which contains the submit handler.

import React, { Component } from 'react';
import { 
  FormGroup, 
  ControlLabel, 
  FormControl, 
  HelpBlock, 
  Button,
  Modal,
  Popover,
  Tooltip,
  OverlayTrigger
} from 'react-bootstrap';
import style from './style';
import FallibleOperationResult from './FallibleOperationResult';
import ModalMessageBox from './ModalMessageBox';
import ReactDOM from 'react-dom';

class SignUpForm extends Component {
  constructor(props) {
    super(props)
    this.state = {email: ''};
    this.handleEmailChange = this.handleEmailChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleEmailChange(evt) {
    this.setState({ email: evt.target.value });
  }
  handleSubmit(evt) {
    evt.preventDefault()
    var email = this.state.email
    var userCreationResult = this.createUser(email)
    if (!userCreationResult.success) {
      displayUserCreationError(userCreationResult)
      console.log("Error detected")
      return
    }

    console.log("Submit button pressed, e-mail: " + this.state.email)
  }
  displayUserCreationError(userCreationResult) {
    // Display of the moal dialog should be implemented here
    // var dialog = new ModalMessageBox();
    // ReactDOM.render(dialog, document.getElementById('root'));
    console.log("User cannot be created ('" + userCreationResult + "'");

    return;
  }
  createUser(email) {
    return new FallibleOperationResult(
      false, 
      'User ' + email + ' cannot be created', 
      undefined
    );
  }
  render() {
    return (
      <div style={style.signUpForm}>
        <form onSubmit={ this.handleSubmit }>
          <FormGroup
            controlId="formBasicText"
          >
          <FormGroup>
            <ControlLabel>Email address</ControlLabel>
            <FormControl 
              type="email" 
              placeholder="Enter email"
              onChange={ this.handleEmailChange }
            />
          </FormGroup>
          <Button type="submit">Sign Up</Button>
          <p>Your password will be sent to your e-mail address.</p>
          </FormGroup>
        </form>
      </div>
    )
  }
}

export default SignUpForm;

I'm new to JavaScript and ReactJS.

I have an application, in which the user enters his or her e-mail address. Then I try to create the user record. If something goes wrong, I want to display a modal window with the error message.

handleSubmit(evt) {
  evt.preventDefault()
  var email = this.state.email
  var userCreationResult = this.createUser(email)
  if (!userCreationResult.success) {
    // The modal window should be displayed here
    return
  }
}

react-bootstrap has a ponent for modal windows. I created a class based on it:

import React, { Component, Modal } from 'react';

class ModalMessageBox extends Component {
  constructor() {
    super()
  }
  render() {
    return (
      <div>
        <Modal>
          <Modal.Header closeButton>
            <Modal.Title>Modal heading</Modal.Title>
          </Modal.Header>
          <Modal.Body>
            <h4>An error occured</h4>
            <p>Test error message.</p>
          </Modal.Body>
        </Modal>
      </div>
    )
  }
}

export default ModalMessageBox;

When the user creation error occurs, I try to display it using this code:

handleSubmit(evt) {
  evt.preventDefault()
  var email = this.state.email
  var userCreationResult = this.createUser(email)
  if (!userCreationResult.success) {
    var dialog = new ModalMessageBox();
    ReactDOM.render(dialog, document.getElementById('root'));

This doesn't work -- I get the error ReactDOM.render(): Invalid ponent element..

What is the right way to display a modal dialog in React?

Update 1 (27.07.2017 15:27 MSK):

Class, which contains the submit handler.

import React, { Component } from 'react';
import { 
  FormGroup, 
  ControlLabel, 
  FormControl, 
  HelpBlock, 
  Button,
  Modal,
  Popover,
  Tooltip,
  OverlayTrigger
} from 'react-bootstrap';
import style from './style';
import FallibleOperationResult from './FallibleOperationResult';
import ModalMessageBox from './ModalMessageBox';
import ReactDOM from 'react-dom';

class SignUpForm extends Component {
  constructor(props) {
    super(props)
    this.state = {email: ''};
    this.handleEmailChange = this.handleEmailChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleEmailChange(evt) {
    this.setState({ email: evt.target.value });
  }
  handleSubmit(evt) {
    evt.preventDefault()
    var email = this.state.email
    var userCreationResult = this.createUser(email)
    if (!userCreationResult.success) {
      displayUserCreationError(userCreationResult)
      console.log("Error detected")
      return
    }

    console.log("Submit button pressed, e-mail: " + this.state.email)
  }
  displayUserCreationError(userCreationResult) {
    // Display of the moal dialog should be implemented here
    // var dialog = new ModalMessageBox();
    // ReactDOM.render(dialog, document.getElementById('root'));
    console.log("User cannot be created ('" + userCreationResult + "'");

    return;
  }
  createUser(email) {
    return new FallibleOperationResult(
      false, 
      'User ' + email + ' cannot be created', 
      undefined
    );
  }
  render() {
    return (
      <div style={style.signUpForm}>
        <form onSubmit={ this.handleSubmit }>
          <FormGroup
            controlId="formBasicText"
          >
          <FormGroup>
            <ControlLabel>Email address</ControlLabel>
            <FormControl 
              type="email" 
              placeholder="Enter email"
              onChange={ this.handleEmailChange }
            />
          </FormGroup>
          <Button type="submit">Sign Up</Button>
          <p>Your password will be sent to your e-mail address.</p>
          </FormGroup>
        </form>
      </div>
    )
  }
}

export default SignUpForm;
Share Improve this question edited Apr 17, 2018 at 9:55 Joshua 3,2063 gold badges26 silver badges41 bronze badges asked Jul 27, 2017 at 12:20 Glory to RussiaGlory to Russia 18.8k60 gold badges200 silver badges344 bronze badges 3
  • the entire application should have only one ReactDOM.render. you must switch between what to show and what not to show – Jefree Sujit Commented Jul 27, 2017 at 12:24
  • 1 can you provide the code/class which has the submitHandler, so that it would be helpful.. – Jefree Sujit Commented Jul 27, 2017 at 12:25
  • @JefreeSujit Yes, see update 1. – Glory to Russia Commented Jul 27, 2017 at 12:30
Add a ment  | 

1 Answer 1

Reset to default 1

The entire application should have only one ReactDOM.render. you must switch between what to show and what not to show based on state.

Since you didnt provide the parent class, i m assuming and giving instruction on my own.

handleSubmit(evt) {
  evt.preventDefault()
  var email = this.state.email
  var userCreationResult = this.createUser(email)
  if (!userCreationResult.success) {
    // The modal window should be displayed here
    // you must set the state here
    this.setState({
      userFailed: true
    });
    return
  }
}

and in the render:

render() {
  return (
    <div>
       // your usual code here
       // render the modal based on state here
       { this.state.userFailed ? < ModalMessageBox /> : null }
    </div>
  )
}

Updated:

import React, { Component } from 'react';
    import { 
      FormGroup, 
      ControlLabel, 
      FormControl, 
      HelpBlock, 
      Button,
      Modal,
      Popover,
      Tooltip,
      OverlayTrigger
    } from 'react-bootstrap';
    import style from './style';
    import FallibleOperationResult from './FallibleOperationResult';
    import ModalMessageBox from './ModalMessageBox';
    import ReactDOM from 'react-dom';

    class SignUpForm extends Component {
      constructor(props) {
        super(props)
        this.state = {
          email: '',
          userCreationFailed: false
        };
        this.handleEmailChange = this.handleEmailChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.displayUserCreationError = this.displayUserCreationError.bind(this);
      }
      handleEmailChange(evt) {
        this.setState({ email: evt.target.value });
      }
      handleSubmit(evt) {
        evt.preventDefault()
        var email = this.state.email
        var userCreationResult = this.createUser(email)
        if (!userCreationResult.success) {
          displayUserCreationError(userCreationResult)
          console.log("Error detected")
          return
        }
        
        console.log("Submit button pressed, e-mail: " + this.state.email)
      }
      displayUserCreationError(userCreationResult) {
        this.setState({
          userCreationFailed: true
        });
        console.log("User cannot be created ('" + userCreationResult + "'");
            
        return;
      }
      createUser(email) {
        return new FallibleOperationResult(
          false, 
          'User ' + email + ' cannot be created', 
          undefined
        );
      }
      render() {
        return (
          <div style={style.signUpForm}>
            <form onSubmit={ this.handleSubmit }>
              <FormGroup
                controlId="formBasicText"
              >
              <FormGroup>
                <ControlLabel>Email address</ControlLabel>
                <FormControl 
                  type="email" 
                  placeholder="Enter email"
                  onChange={ this.handleEmailChange }
                />
              </FormGroup>
              <Button type="submit">Sign Up</Button>
              <p>Your password will be sent to your e-mail address.</p>
              </FormGroup>
            </form>
            {this.state.userCreationFailed ? <ModalMessageBox /> : undefined}
          </div>
        )
      }
    }

    export default SignUpForm;
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/react/15.1.0/react-dom.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论