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

"Execution of the console.log statement occurs following the completion of the request handling

When I have a piece of middleware that responds if no token is found, why does the console.log line still run after the request is responded to? I always believed that the res.json call would "end" the middleware. Any insights on this behavior would be g ...

What could be causing my randomly generated value to be overwritten so quickly?

I'm encountering an issue with my code. I am attempting to generate objects in random locations using drawHyperBall(), getRandomIntX(), and getRandomIntY(). However, the random value seems to be constantly overwritten. How can I resolve this problem? ...

Is installing Npm outside the designated client directory leading to data corruption?

I'm facing an issue in my full stack environment using node.js/react. In my project, I have a client folder named 'client' which has its own node modules file. Whenever I need to install a package, I navigate into the client folder and run n ...

iOS devices featuring the scroll function allows for seamless navigation and effortless

Here is the code snippet that I am using: $(document).scroll(function() { thedistance(); }); I would like thedistance() to trigger while a user is scrolling on an iOS device, however, it currently only fires after the scrolling has stopped, rather t ...

Retrieve the $$state value from the Service Function

I am new to Angular and struggling to understand a function in my service. I have this code snippet: checkRoomNameStatus: function() { var promises = []; var emptyRooms = []; DatabaseService.openDB().transaction(function(tx) { tx.exec ...

After receiving a data token from the server in one controller, how can I efficiently utilize that token in a different AngularJS controller?

In my adminSearchCtrl controller, I am receiving data from the server in the form of a token and want to pass that token to another controller named "adminViewCtrl". How can I achieve this? adminSearchCtrl.js $scope.getUserDetails = function(selectedUser ...

What is the best way to implement multilanguage support in nodejs without relying on cookies or external modules?

Currently, I am in the process of transitioning all my projects to node.js in order to enhance my JavaScript skills. Using Node.js along with the Express module, one of my clients who runs a translation company has requested that I incorporate two language ...

When utilizing res.redirect in Express, an error is triggered stating "Uncaught SyntaxError: Unexpected token <""

Utilizing Node.js, Express, Socket.io, firebase admin+auth, and Handlebars. An error Uncaught SyntaxError: Unexpected token < keeps popping up. Whenever I use res.redirect('/login');, I encounter the error. It disappears when I remove res.re ...

What is the most effective method for informing the browser about changes in the database?

I've been working with django for about 6 months now and it has been effective for the websites I create. However, I recently encountered an issue while developing a website where users receive notifications whenever another user updates a blog post. ...

Displaying a preloaded image on the canvas

Once again, I find myself in unfamiliar territory but faced with the task of preloading images and then displaying them on the page once all elements (including xml files etc.) are loaded. The images and references are stored in an array for later retrie ...

Function not executed right away

One of the functions I have is called showLoading(). This function is responsible for displaying a spinner by adding a specific class to the body: function showLoading(){ //console.log("show loading"); loading = true; $("body").addClass("loadi ...

Issue encountered when implementing promise and await within a Vue method

I've implemented a function in the mounted() hook to fetch files from my Dropbox account using a promise. Once the promise is resolved successfully, I iterate through all the files and execute another promise function to retrieve additional informatio ...

Dispatch a personalized event using WebSockets

Recently, I've been exploring how to listen for a custom event using native websockets on the client side and utilizing the ws module on the back end. To start off, I create a pool of connected clients. import express from 'express' import ...

Using react testing to access the redux store

Currently, I am facing a challenge with the following test scenario. import React from 'react'; import { render } from '@testing-library/react'; import { Provider } from 'react-redux'; import {store} from '../../app/sto ...

Best practice for passing a function with parameters as a prop in React

When attempting to pass a function with parameters as props from a Parent component to a Child component using the following syntax: handleClick={() => handleClick(tiposObjetivos.RENTA_TEMPORAL)} The Child component will keep re-rendering each time th ...

Decoding JSON on 9gag

I am trying to select a random image from the following URL: In order to display it correctly, I need to determine the size of the image. I am utilizing YQL to store the JSON result in a variable (referred to as source). After replacing 'https&apos ...

What steps should be taken to prepare data for transmission to a server in a Next.js environment?

I'm in the process of creating a website that requires authentication. I am using Next (React) and typescript for web development. My objective is to make most pages ServerSideRendered or StaticHTML. However, I encountered an issue right at the begin ...

Ways to manage an excessive number of asynchronous calls?

As a newcomer to Node, I've learned that writing synchronous functions can negatively impact the event loop by causing it to lock up. It's generally better to write everything asynchronously. However, there are cases where using async for everyt ...

Using the react-router Navigate component within a Next.js application allows for seamless

Is there a way to achieve the same result as the Navigate component in react-router within Nextjs? The next/Router option is available, but I am looking for a way to navigate by returning a component instead. I need to redirect the page without using rout ...

What is the best way to reset local state after triggering a success action in Redux Saga?

I'm looking to reset my component state after a successful call in redux saga. Is there a way to achieve this? Currently, I am using the component state to track my input value. this.state = { department: '', }; The solution I have im ...