search
HomeWeb Front-endFront-end Q&AHow to implement pop-up modal box in react

React method to implement a pop-up modal box: 1. Use createPortal to render the element directly under "document.body"; 2. Use "modelShow" and "modelShowAync" to control the display and hiding of the pop-up window; 3. , just use a controller controlShow to smoothly perform the update task.

How to implement pop-up modal box in react

The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.

How to implement pop-up modal box in react?

React to implement Modal pop-up window

1. Dialog.js file

import React, {useMemo, useEffect, useState} from 'react'
import ReactDOM from 'react-dom'
/**
 *
 * 需要把元素渲染到组件之外,用 createPortal 把元素直接渲染到 document.body 下,为了防止函数组件每一次执行都触发 createPortal, 所以通过 useMemo 做性能优化。
 因为需要渐变的动画效果,所以需要两个变量 modelShow / modelShowAync 来控制显示/隐藏,modelShow 让元素显示/隐藏,modelShowAync 控制动画执行。
 当弹窗要显示的时候,要先设置 modelShow 让组件显示,然后用 setTimeout 调度让 modelShowAync 触发执行动画。
 当弹窗要隐藏的时候,需要先让动画执行,所以先控制 modelShowAync ,然后通过控制 modelShow 元素隐藏,和上述流程相反。
 用一个控制器 controlShow 来流畅执行更新任务。
 */
// 控制弹窗隐藏以及动画效果
const controlShow = (f1, f2, value, timer) => {
    f1(value)
    return setTimeout(() => {
        f2(value)
    }, timer)
}
export const Dialog = (props) => {
    const {width, visible, closeCb, onClose} = props
    // 控制 modelShow动画效果
    const [modelShow, setModelShow] = useState(visible)
    const [modelShowAsync, setModelShowAsync] = useState(visible)
    const renderChildren = useMemo(() => {
        // 把元素渲染到组件之外的document.body 上
        return ReactDOM.createPortal(<div style={{display: modelShow ? &#39;block&#39; : &#39;none&#39;}}>
            <div className="model_container" style={{opacity: modelShowAsync ? 1 : 0}}>
                <div className="model_wrap">
                    <div style={{width: width + &#39;px&#39;}}> {props.children} </div>
                </div>
            </div>
            <div className="model_container mast" onClick={() => onClose && onClose()}
                 style={{opacity: modelShowAsync ? 0.6 : 0}}/>
        </div>, document.body)
    }, [modelShow, modelShowAsync])
    useEffect(() => {
        let timer
        if (visible) {
            // 打开弹窗,
            timer = controlShow(setModelShow, setModelShowAsync, visible, 30)
        } else {
            timer = controlShow(setModelShowAsync,setModelShow,visible,1000)
        }
        return () => {
            timer && clearTimeout(timer)
        }
    }, [visible])
    return renderChildren
}

2. Modal.js

import {Dialog} from "./Dialog";
import React, {useEffect, useState} from &#39;react&#39;
import ReactDOM from &#39;react-dom&#39;
import &#39;./style.scss&#39;
class Modal extends React.PureComponent {
    // 渲染底部按钮
    renderFooter = () => {
        const {onOk, onCancel, cancelText, okText, footer} = this.props
        //    触发onOk / onCancel回调
        if (footer && React.isValidElement(footer)) return footer
        return <div className="model_bottom">
            <div className="model_btn_box">
                <button className="searchbtn"
                        onClick={(e) => {
                            onOk && onOk(e)
                        }}>{okText || &#39;确定&#39;}
                </button>
                <button className="concellbtn"
                        onClick={(e) => {
                            onCancel && onCancel(e)
                        }}>{cancelText || &#39;取消&#39;}
                </button>
            </div>
        </div>
    }
    // 渲染底部
    renderTop = () => {
        const {title, onClose} = this.props
        return <div className="model_top">
            <p>{title}</p>
            <span className="model_top_close" onClick={() => onClose && onClose()}>X</span>
        </div>
    }
    // 渲染弹窗内容
    renderContent = () => {
        const {content, children} = this.props
        return React.isValidElement(content) ? content : children ? children : null
    }
    render() {
        const {visible, width = 500, closeCb, onClose} = this.props
        return <Dialog
            closeCb={closeCb}
            onClose={onClose}
            visible={visible}
            width={width}
        >
            {this.renderTop()}
            {this.renderContent()}
            {this.renderFooter()}
        </Dialog>
    }
}
// 静态方法
let ModalContainer = null
const modelSymbol = Symbol(&#39;$$_model_Container_hidden&#39;)
// 静态属性show——控制
Modal.show = (config) => {
    //  如果modal已经存在,name就不需要第二次show
    if (ModalContainer) return
    const props = {...config, visible: true}
    const container = ModalContainer = document.createElement(&#39;div&#39;)
    // 创建一个管理者,管理model状态
    const manager = container[modelSymbol] = {
        setShow: null,
        mounted: false,
        hidden() {
            const {setShow} = manager
            setShow && setShow(false)
        },
        destroy() {
            //    卸载组件
            ReactDOM.unmountComponentAtNode(container)
            // 移除节点
            document.body.removeChild(container)
            // 置空元素
            ModalContainer = null
        }
    }
    const ModelApp = (props) => {
        const [show, setShow] = useState(false)
        manager.setShow = setShow
        const {visible, ...trueProps} = props
        useEffect(() => {
            // 加载完成,设置状态
            manager.mounted = true
            setShow(visible)
        }, [])
        return <Modal {...trueProps} closeCb={() => manager.mounted && manager.destroy()} visible={show}/>
    }
    // 插入到body中
    document.appendChild(container)
    // 渲染React元素
    ReactDOM.render(<ModelApp/>, container)
    return manager
}
Modal.hidden = () => {
    if(!ModalContainer) return
    // 如果存在ModalContainer 那么隐藏ModalContainer
    ModalContainer[modelSymbol] && ModalContainer[modelSymbol].hidden()
}
export default Modal

3. style.scss style file

$bg-linear-gradien-red-light : linear-gradient(135deg, #fc4838 0%, #f6346b  100%);
$bg-linear-gradien-red-dark : linear-gradient(135deg, #fc4838 0%, #f6346b  100%);
.constrol{
  padding: 30px;
  width: 500px;
  border: 1px solid #ccc;
  height: 200px;
}
.feel{
  padding: 24px;
}
.model_top{
  height: 40px;
  border-radius: 5px  5px 0 0 ;
  position: relative;
  p{
    height: 40px;
    font-weight: bold;
    line-height: 40px;
    padding-left: 14px;
  }
  background-color: #eee;
  .model_top_close{
    position: absolute;
    font-size: 16px;
    cursor: pointer;
    right: 24px;
    top: 8px;
  }
}
.model_bottom{
  height: 50px;
  padding-top: 10px;
  .model_btn_box{
    display: inline-block;
    margin-left: 50%;
    transform: translateX(-50%);
  }
}
.model_container{
  .model_wrap{
    position: absolute;
    border-radius:5px ;
    background: #fff;
    left:50%;
    top:50%;
    transform: translate(-50%,-50%);
  }
  position: fixed;
  z-index: 10000;
  left:0;
  top:0;
  transition: opacity 0.3s;
  right: 0;
  bottom: 0;
}
.mast{
  background-color: #000;
  z-index: 9999;
}
.searchbtn{
  background: linear-gradient(135deg, #fc4838 0%, #f6346b  100%);
  color: #fff;
  min-width: 96px;
  height :36px;
  border :none;
  border-radius: 18px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  margin-left: 20px !important;
}
.searchbtn:focus{
  background: $bg-linear-gradien-red-dark;
  color: #fff;
  min-width: 96px;
  height: 36px;
  border: none;
  border-radius: 18px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  margin-left: 20px !important;
  box-shadow: 0 2px 7px 0 #FAA79B;
}
.searchbtn:hover{
  background :$bg-linear-gradien-red-light;
  color :#fff;
  min-width: 96px;
  height :36px;
  margin-left: 20px !important;
  border: none;
  border-radius: 18px;
  font-size :14px;
  font-weight: 500;
  cursor: pointer;
  box-shadow: 0 2px 7px 0 #FAA79B;
}
.searchbtn:disabled{
  background: #c0c6c6;
  color :#fff;
  min-width: 96px;
  height :36px;
  font-size :14px;
  font-weight: 500;
  border: none;
  border-radius: 18px;
  cursor: not-allowed;
}
.concellbtn{
  background :#fff;
  color :#303133;
  width: 96px;
  height: 36px;
  font-size: 14px;
  font-weight: 500;
  border :1px solid #E4E7ED;
  border-radius: 18px;
  cursor: pointer;
  // margin-right: 10px;
  margin-left: 10px;
}
.concellbtn:hover{
  background :rgba(220, 223, 230, 0.1);
  color: #303133;
  width :96px;
  height: 36px;
  font-size: 14px;
  font-weight: 500;
  border :1px solid #E4E7ED;
  border-radius: 18px;
  cursor: pointer;
  // margin-right: 10px;
  margin-left: 10px;
}
.concellbtn:focus{
  background :rgba(220, 223, 230, 0.24);
  color: #303133;
  width :96px;
  height: 36px;
  font-size: 14px;
  font-weight: 500;
  border: 1px solid #C0C4CC;
  border-radius: 18px;
  cursor: pointer;
  margin-right: 10px;
  margin-left: 10px;
}

4. Calling example

import React, {useState, useMemo} from &#39;react&#39;
import Modal from &#39;./customPopup/Modal&#39;
/* 挂载方式调用modal */
export default function App() {
    const [ visible , setVisible ] = useState(false)
    const [ nameShow , setNameShow ] = useState(false)
    const handleClick = () => {
        setVisible(!visible)
        setNameShow(!nameShow)
    }
    /* 防止 Model 的 PureComponent 失去作用 */
    const [ handleClose ,handleOk, handleCancel ] = useMemo(()=>{
        const Ok = () =>  console.log(&#39;点击确定按钮&#39;)
        const Close = () => setVisible(false)
        const Cancel = () => console.log(&#39;点击取消按钮&#39;)
        return [Close , Ok , Cancel]
    },[])
    return <div>
        <Modal
            onCancel={handleCancel}
            onClose={handleClose}
            onOk={handleOk}
            title={&#39;标题&#39;}
            visible={visible}
            width={700}
        >
            <div className="feel" >
              内容。。。。。。。
            </div>
        </Modal>
        <button onClick={() => {
            setVisible(!visible)
            setNameShow(false)
        }}
        > model show </button>
        <button onClick={handleClick} > model show ( 显示作者 ) </button>
    </div>
}

Achieve effect

How to implement pop-up modal box in react

Recommended learning: "react video tutorial"

The above is the detailed content of How to implement pop-up modal box in react. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS: Can I use multiple IDs in the same DOM?CSS: Can I use multiple IDs in the same DOM?May 14, 2025 am 12:20 AM

No,youshouldn'tusemultipleIDsinthesameDOM.1)IDsmustbeuniqueperHTMLspecification,andusingduplicatescancauseinconsistentbrowserbehavior.2)Useclassesforstylingmultipleelements,attributeselectorsfortargetingbyattributes,anddescendantselectorsforstructure

The Aims of HTML5: Creating a More Powerful and Accessible WebThe Aims of HTML5: Creating a More Powerful and Accessible WebMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebcapabilities,makingitmoredynamic,interactive,andaccessible.1)Itsupportsmultimediaelementslikeand,eliminatingtheneedforplugins.2)Semanticelementsimproveaccessibilityandcodereadability.3)Featureslikeenablepowerful,responsivewebappl

Significant Goals of HTML5: Enhancing Web Development and User ExperienceSignificant Goals of HTML5: Enhancing Web Development and User ExperienceMay 14, 2025 am 12:18 AM

HTML5aimstoenhancewebdevelopmentanduserexperiencethroughsemanticstructure,multimediaintegration,andperformanceimprovements.1)Semanticelementslike,,,andimprovereadabilityandaccessibility.2)andtagsallowseamlessmultimediaembeddingwithoutplugins.3)Featur

HTML5: Is it secure?HTML5: Is it secure?May 14, 2025 am 12:15 AM

HTML5isnotinherentlyinsecure,butitsfeaturescanleadtosecurityrisksifmisusedorimproperlyimplemented.1)Usethesandboxattributeiniframestocontrolembeddedcontentandpreventvulnerabilitieslikeclickjacking.2)AvoidstoringsensitivedatainWebStorageduetoitsaccess

HTML5 goals in comparison with older HTML versionsHTML5 goals in comparison with older HTML versionsMay 14, 2025 am 12:14 AM

HTML5aimedtoenhancewebdevelopmentbyintroducingsemanticelements,nativemultimediasupport,improvedformelements,andofflinecapabilities,contrastingwiththelimitationsofHTML4andXHTML.1)Itintroducedsemantictagslike,,,improvingstructureandSEO.2)Nativeaudioand

CSS: Is it bad to use ID selector?CSS: Is it bad to use ID selector?May 13, 2025 am 12:14 AM

Using ID selectors is not inherently bad in CSS, but should be used with caution. 1) ID selector is suitable for unique elements or JavaScript hooks. 2) For general styles, class selectors should be used as they are more flexible and maintainable. By balancing the use of ID and class, a more robust and efficient CSS architecture can be implemented.

HTML5: Goals in 2024HTML5: Goals in 2024May 13, 2025 am 12:13 AM

HTML5'sgoalsin2024focusonrefinementandoptimization,notnewfeatures.1)Enhanceperformanceandefficiencythroughoptimizedrendering.2)Improveaccessibilitywithrefinedattributesandelements.3)Addresssecurityconcerns,particularlyXSS,withwiderCSPadoption.4)Ensur

What are the main areas where HTML5 tried to improve?What are the main areas where HTML5 tried to improve?May 13, 2025 am 12:12 AM

HTML5aimedtoimprovewebdevelopmentinfourkeyareas:1)Multimediasupport,2)Semanticstructure,3)Formcapabilities,and4)Offlineandstorageoptions.1)HTML5introducedandelements,simplifyingmediaembeddingandenhancinguserexperience.2)Newsemanticelementslikeandimpr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use