Modal in React JS

Asked

Viewed 728 times

1

Good morning, you guys! I have a form, on the button to save the data of the same I call a modal component asking if the user really wants to perform the operation. The question is: I don’t know how to call the save function on the modal "yes" button if the user wants to save the operation.

Follows the codes:

Form Code:

import React, { useState, useEffect } from 'react';
import useApi from '../../utils/useApi'
import { useHistory } from 'react-router-dom'

import Modal from '../../modals/modal'
import './Form.css'

const initialValue = {
    title: "",
    url: "",
    imageUrl: "",
    price: 0,
}

const PromotionForm = ({ id }) => {
    const [values, setValues] = useState(id ? null : initialValue)
    const [isModalVisible, setisModalVisible] = useState(false)
    const history = useHistory()


    const [load] = useApi({
        url: `/promotions/${id}`,
        method: 'get',
        onCompleted: (res) => {
            setValues(res.data)
        }
    })

    const [save, saveInfo] = useApi({
        url: id
            ? `promotions/${id}`
            : '/promotions',
        method: id ? 'put' : 'post',
        onCompleted: (res) => {
            if (!res.error) {
                history.push('/')
            }
        }
    })

    useEffect(() => {
        if (id) {
            load()
        }
    }, [id])

    function onChange(ev) {
        const { name, value } = ev.target
        //console.log({name, value})

        setValues({ ...values, [name]: value })
    }

    function onSubmit(ev) {
        ev.preventDefault()
        save({
            data: values
        })
    }

    return (
        <div>
            <h1> Site Promoção </h1>
            <h2> Nova Promoção </h2>
            {!values
                ? (
                    <div>Carregando...</div>
                ) : (
                    <form onSubmit={onSubmit}>


                        {saveInfo.loading && <span>Salvando Dados...</span>}

                        <div className="promotion-form__group">
                            <label htmlFor="title">Título</label>
                            <input
                                id="title"
                                name="title"
                                type="text"
                                onChange={onChange}
                                value={values.title}
                            />
                        </div>

                        <div className="promotion-form__group">
                            <label htmlFor="url">Link</label>
                            <input
                                id="url"
                                name="url"
                                type="text"
                                onChange={onChange}
                                value={values.url}
                            />
                        </div>

                        <div className="promotion-form__group">
                            <label htmlFor="imageUrl">Imagem (URL)</label>
                            <input
                                id="imageUrl"
                                name="imageUrl"
                                type="text"
                                onChange={onChange}
                                value={values.imageUrl}
                            />
                        </div>

                        <div className="promotion-form__group">
                            <label htmlFor="price">Preço</label>
                            <input
                                id="price"
                                name="price"
                                type="number"
                                onChange={onChange}
                                value={values.price}
                            />
                        </div>

                        <div className="app">
                            {/* <button type="submit" className=""> Salvar </button> */}

                            <button type="button" onClick={() => setisModalVisible(true)}> Salvar </button>
                            {isModalVisible ? (
                                <Modal onClose={() => { setisModalVisible(false) }}>  </Modal>
                            )
                                : null}

                        </div>

                    </form>

                )}

        </div>

    );
}
export default PromotionForm;


Modal Code:

import React from 'react'
import './Styles.scss'

const Modal = ({ onClose = () => {}, Children }) => {
    
    return (
        <div className="modal" onClick={onClose}>
            <div className="container">

                <button className="x" onClick={onClose}></button>              
                <div className="content"> <h1> Deseja Salvar? </h1> </div>
            
                <button className="closeModal" >Sim</button>
                <button className="closeModal" onClick={onClose}>Não</button>
            </div>  
        </div>
    )            
}

export default Modal

1 answer

2

Your Modal component receives an onClose property that contains a function executed when the user clicks on the Modal closure button. To perform a function when the user clicks on the 'Yes' button, the logic is exactly the same.

Add a property for the 'yes' event in the Modal component:

// ...

const Modal = ({ onClose = () => {}, onYes = () => {}, Children }) => {
    
                // ...
                <button className="closeModal" onClick={onYes}>Sim</button>
                // ...

When using Modal, use:

 <Modal onClose={() => { setisModalVisible(false) }}
        onYes={submit}>

And create a callback with the name Submit that calls the save method.

  • Oops!!! Perfect, it worked!!! Thank you very much!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.