Search code examples
javascriptreactjsbootstrap-4react-bootstrap

How to remove the modal after validation


Goal:
When you press on the submit button, inside of modal, and if the validation is OK, then the modal popup to be be removed.
You should enable to reuse the modal again but for another row.

Problem:
I tried to remove the modal but after that the function do not work when you tried another row in the table.
What part of the code am I missing?

Info:
*Newbie in reactjs

Dependencies:
"bootstrap": "^4.6.0",
"react": "^17.0.2",
"react-bootstrap": "^1.6.1",
"react-dom": "^17.0.2",
"react-router-dom": "^5.2.0",
"react-scripts": "4.0.3",

Thank you!


import './App.css';
import Tenant from './components/Tenant';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
import 'bootstrap/dist/css/bootstrap.min.css';

function App() {
  return (
    <Router>
      <div className="App">
        <Link to="/Tenant">Guest</Link>
        <div>
          <Route path="/tenant" component={Tenant} />
        </div>
      </div>
    </Router>

  );
}

export default App;

import React, { Component } from 'react';
import ModalForm from './ModalForm';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

export default class Tenant extends Component { 
  constructor() {
    super();
  }

  state = {
    isLoaded: false,
    listTenant: {},
    isOpen: false,
    title: "",
    body: ""
  };

  openModal(titleData, bodyData) {

    this.setState({ isOpen: true });
    this.setState({ title: titleData });
    this.setState({ body: bodyData });
  }

  closeModal = () => this.setState({ isOpen: false });  
 
  componentDidMount() {
    fetch("https://jsonplaceholder.typicode.com/posts")
    .then(results => results.json())
    .then(data => this.setState({
      isLoaded: true,
      listTenant: data,
    }))
    .catch(err => console.log(err)) 
  }

  render() {
    const listTenant = this.state.listTenant;
    const { isLoaded } = this.state;

    if (!isLoaded) {
      return (<div>Loading...</div>);
    } else {
      return (
        <div>
          <table>
            <thead>
              <tr>
                <th>Id</th>
                <th>userId</th>
                <th>title</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
            {
              this.state.listTenant &&
              this.state.listTenant.map((item) => {
                return (
                  <tr key={item.id.toString()}>
                    <td>{item.id}</td>
                    <td>{item.userId}</td>
                    <td>{item.title}</td>
                    <td>
                      <button className="btn btn-primary" onClick={() => this.openModal(item.id, item.title)} >Display Modal Form</button>
                    </td>
                  </tr>          
                );
              })
            }
            </tbody>
          </table>

          {
            this.state.isOpen ?
            <ModalForm
            closeModal={this.closeModal}
              isOpen={this.state.isOpen}
              title= {this.state.title}
              body= {this.state.body}
            />
            :
            null
          }
        </div>
      );
    } 
  }
}

import Form from 'react-bootstrap/Form'
import Modal from 'react-bootstrap/Modal'
import Button from 'react-bootstrap/button'
import React, { Component } from 'react';

export default class ModalForm extends Component {

  constructor(props) {
    super(props);
  }

  state= { 
    name: '',
    title: this.props.title,
    body: this.props.body,
  }

  handleChange = (e) => this.setState({name: e.target.value})

  handleSubmit = () => {
    console.log(this.state.name);

    if (this.state.name == 'aa')
    {
        alert("aa");
        // close this modal
    }
    else
    {
        alert("validation is error");
    }
  };

  render() {

    return(
      <Modal 
        show={this.props.isOpen} 
        onHide={this.props.closeModal}
      >
        <Modal.Header closeButton>
          <Modal.Title>{this.state.title}</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <Form.Group >
            <Form.Label>Name: </Form.Label>
            <Form.Control type="text" onChange={this.handleChange} value={this.state.name} placeholder="name input"/>
            { this.state.body }   
          </Form.Group>
        </Modal.Body>
        <Modal.Footer>
          <Button variant="primary" type="submit" onClick={this.handleSubmit}>
            Submit
          </Button>
        </Modal.Footer>
      </Modal>
    )
  }
}

Solution

  • Just add this.props.closeModal

    handleSubmit = () => {
      console.log(this.state.name);
      if (this.state.name == "aa") {
        alert("aa");
        // close this modal
        this.props.closeModal();
      } else {
        alert("validation is error");
      }
    };