What is the best way to dismiss the modal window in React upon clicking the "Add product" button?

Hello all, I'm having trouble figuring out how to close the modal window in React. I want it so that when the user clicks on the "Add" button, a modal window opens for data input, and then upon clicking the "Add product" button, the window closes immediately.

Here is the code snippet:

import React from 'react';
import CatalogProducts from "./CatalogProducts";
import Info from "./Info";
import CreateProduct from "./CreateProduct";
import {Button} from 'react-bootstrap';
import Popup from 'reactjs-popup';
import 'reactjs-popup/dist/index.css';
import '../css/popup.css'

const Main = () => {

    return (
        <div>
            <div className="d-flex justify-content-between" style={{ width: '33rem', margin: '10px' }}>
                <Popup contentStyle={{width: "unset", backgroundColor: "red", border: "none", background: "none"}}
                       trigger={<Button> Add </Button>} modal>
                    <CreateProduct/>
                </Popup>
                <input placeholder={'search'}/>
                <span>sort by</span>
                <input/>
            </div>
            <CatalogProducts></CatalogProducts>
            <Info></Info>
        </div>
    );

};

export default Main;


import React from 'react';
import {useDispatch} from "react-redux";
import {addProductAction} from "../action/productsAction";
import {ConfigProduct} from "../Utils/configProduct";
import '../css/popup.css'
import '../css/flex.css'
import {Button} from "react-bootstrap";

const CreateProduct = () => {

    const dispatch = useDispatch()
    const newProduct = new ConfigProduct()
    
    function addProd() {
        dispatch(addProductAction(newProduct))
    }
    
    return (
            <div className = "popup">
                <h2  style={{textAlign: "center", color: "red"}}>New product</h2>
                <input className="item" placeholder="id" onChange={e => newProduct.idProd = e.target.value}/>
                <input className="item" placeholder="info" onChange={e => newProduct.name = e.target.value}/>
                <input className="item" placeholder="price" onChange={e => newProduct.infoProd = e.target.value}/>
                <input className="item" placeholder="date" onChange={e => newProduct.price = e.target.value}/>
                <input className="item" placeholder="enter url" onChange={e => newProduct.date = e.target.value}/>
                <p>
                    <Button onClick={addProd}>Add product</Button>
                </p>
            </div>
    );

};

export default CreateProduct;

I attempted to use a flag to switch the component class, but unfortunately, it did not produce the desired result.

Answer №1

To implement in your main JavaScript file:

const [open, setOpen] = useState(false);

const closeModal = () => setOpen(false);

return (
   <div>
     <div className="d-flex justify-content-between" style={{ width: '33rem', margin: '10px' }}>
       <Popup 
         contentStyle={
           {width: "unset", backgroundColor: "red", border: "none", background: "none"}
          }
          trigger={<Button> Add </Button>} 
          modal
       >
            <CreateProduct closeModal={closeModal}/>
       </Popup>
                    <input placeholder={'search'}/>
                    <span>sort by</span>
                    <input/>
                </div>
                <CatalogProducts></CatalogProducts>
                <Info></Info>
            </div>
    )

In the CreateProduct component:

const CreateProduct = ({ closeModal }) => {
// your code 

function addProd() {
   dispatch(addProductAction(newProduct))
   closeModal()
}

// rest of your code
)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Store my JSON data in a separate file and then reference it in my controller

Hello, I am currently working on an AngularJS application development project. Within my JSON data, I have information structured like this: angular.module('app', []).controller('MainController', ['$scope', function($scope) { ...

Animate.css does not function properly when loaded locally

I'm currently using a Flask server to host an HTML file for testing purposes. Within the head of this HTML file, I have linked to a locally stored animate.min.css file (<link rel="stylesheet" type="text/css" href="{{ url_fo ...

Integrate Thymeleaf properties seamlessly into JavaScript code

I am attempting to embed a property from Spring's application.properties into JavaScript. It is working properly with the following code: <h1 th:utext="${@environment.getProperty('key')}"></h1> However, it returns null with th ...

Typescript check for type with Jest

Assume there is an interface defined as follows: export interface CMSData { id: number; url: string; htmlTag: string; importJSComponent: string; componentData: ComponentAttribute[]; } There is a method that returns an array of this obj ...

Causing a click event to occur results in crashing the browser

Take a look at this link: example on jsfiddle Why does the click event keep triggering multiple times when a div is clicked, eventually causing the browser to crash? What could be causing this issue and how can it be resolved? The actual div contains a l ...

The API results are able to be displayed in the console, but unfortunately cannot be shown on the user interface. Any efforts to map the results will result in an Un

Can anyone help me troubleshoot an issue with displaying information from a free API on my page? I'm developing a cryptocurrency app using React, and while I can see the array data with console.log(response.data), I encounter an error when I try to se ...

Using JavaScript promises to handle connection pooling and query execution

I am contemplating whether this approach is on the right track or if it requires further adjustments. Should I consider promisifying my custom MySQL getConnection method as well? request: function(queryRequest) { return new Promise(function(re ...

Generate a unique sequence not functioning

I'm attempting to generate a unique string composed of random characters, similar to the example found at this source. $(document).ready(function(){ $('#randomize').click(function() { var str = ""; var possibleChars = "michaeljo ...

Is there a way for me to attach a link to a picture displayed in a lightbox that directs to an external ".html" file?

I have a platform where users can view images in a gallery and when they click on an image, it opens up in a lightbox. I am trying to add a feature where the opened image can be clicked again to redirect the user to an external page. I attempted to nest t ...

How can the token be verified when authorizing Google OAuth 2.0 on the server side?

Unable to validate the user token ID on the server side despite following Google's guide at https://developers.google.com/identity/sign-in/web/backend-auth In JavaScript, I retrieve the id token and send it to the server: var googleUser = auth2.cur ...

Updating the title of a page on CoreUI's CBreadcrumbRouter dynamically

I'm currently developing a project with VueJS and the CoreUI admin template. Is there a way I can change the title of the current page as shown on the CBreadcrumbRouter? The GitHub documentation mentions that the script typically displays meta.label ...

Modify the values of all cells within a specific column in a table by utilizing a 2D array for both rows and cells

https://codesandbox.io/s/1p770371j The demonstration above showcases a table where data can be modified in each cell, and the 2D array keeps track of which row and column the data changes occur. A new button has been added to the column header titles. Th ...

Having Trouble Accessing Dialog Ref with React Hooks and Material-UI When useEffect Runs for the First Time

I am facing an issue where I am unable to obtain a reference to the DOM Node of a material-ui Dialog when my component first loads. The reference always returns as undefined. Here is the code snippet: import React, { useEffect, useRef } from "react"; impo ...

Synchronize two div elements with JavaScript

The demonstration features two parent divs, each containing a child div! The first parent div's child div is draggable and resizable using JQueryUI. There are events for both dragEnd and resizeEnd associated with this div. The goal is to synchronize ...

What could be the reason for XMLHttpRequest's readystate being something other than 4?

Currently delving into the realm of AJAX for the first time, and endeavoring to construct a basic application that computes the required grade on a final exam based on past assessment results. The user keys in their grades into the form, subsequent to whi ...

The JSON node fails to return a value after inserting data through an ajax request

I'm encountering an issue with a jQuery plugin that loads JSON data through an AJAX call and inserts it into an existing object. When I attempt to reference the newly inserted nodes, they show up as 'undefined', despite the data appearing co ...

React app experiencing issues with mui icon display upon deployment

I am facing an issue in my app where I am trying to import a mui/icon: import PriceCheckIcon from "@mui/icons-material/PriceCheck"; When running the app locally, the icon appears fine. However, once deployed on Surge or Vercel, the icon does not ...

What is the best way to compare dates in order to obtain the necessary results?

Question : Filter the JSON array to retrieve specific entries 1: All entries with name "Sam". 2: All entries with date "Dec 2019". // JSON Data provided below. var data = [{ "id":"27", "0":{ "name":"Sam", "date":"2021-02-28" ...

Strategies for passing tag ID to onClick function in React

I am trying to pass the id of a <th id='1' onClick={this.click.bind(this)}> tag to an onclick function. The goal is to print the id of the <th> in the console.log within the click() function. Here is the code snippet: <thead> ...

Change the boxShadow and background properties of the material-ui Paper component

I am currently referencing their documentation found at this link in order to customize default Paper component properties. Below is the code snippet I have: import { styled } from '@mui/material/styles'; import { Modal, Button, TextField, Grid, ...