Search code examples
reactjsformsbuttoncomponentssimplemodal

How to submit a form and pop up a modal to display the result in React


I have built a calculation form as the link here https://codesandbox.io/s/calculation-form-uxip8?file=/src/components/Result.jsx

Instead, display the result on another page, I want when the user clicks on the "Calculate saving range" button, there is a pop up modal display the results on the same page

I intend to write Model.jsx

import React from "react";
import { NavLink } from "react-router-dom";

class ShowModal extends React.Component {
  state = {
    open: false,
  };

  onOpenModal = () => {
    this.setState({ open: true });
  };

  onCloseModal = () => {
    this.setState({ open: false });
  };

  render() {
    const { open } = this.state;
return(
       <div className="result">     
        <Modal open={open} onClose={this.onCloseModal}>
           <h2>You could save between</h2>
           <h1>{this.props.location.state.value} Annually</h1>
           <NavLink to="/">Use Calculator Again</NavLink>
        </Modal>
      </div>)

Can anyone stop by and give me any suggestions with my case? And also if I want to write the model.jsx, how to link it into the "Calculate saving range" button? Is it the same way to link another page? Thanks!


Solution

  • Put ShowModal component on the Calculator component then instead of using NavLink on your calculate button, use it to change the state of the Modal to open. So on your handleSubmit

    handleSubmit = (event) => {
      event.preventDefault();
      const isValid = this.validate();
      if (isValid) {
        this.setState({ open: true, value: "$" +
          Math.floor(1.69 * this.state.squareFootage * (10 / 100)) +
          "- $" +
          Math.floor(1.69 * this.state.squareFootage * (30 / 100)) });
     }
    

    };

    Make sure to add value on your state and then pass that value as a prop to the ShowModal component.

    <ShowModal open={this.state.open} value={this.state.value} onClose={this.onClose} />
    

    Your modal component should look like that, accepting 3 props(or more if you have any thing to pass)