front/react

[react] createPortal, Suspense

๋ฐฐ๊ณ ํŒŒ์š” 2026. 1. 1. 20:45
728x90

๐Ÿ“ React Portal

  • ์ปดํฌ๋„ŒํŠธ๋ฅผ DOM Tree์˜ ๋‹ค๋ฅธ ์œ„์น˜์— ๋ Œ๋”๋งํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•˜๋Š” ๊ธฐ๋Šฅ.
  • ๋ชจ๋‹ฌ, ๋ ˆ์ด์–ด ํŒ์—…์—์„œ ๋งŽ์ด ์‚ฌ์šฉํ•จ.

import { useState } from 'react';
import { createRoot } from 'react-dom/client';
import { createPortal } from 'react-dom';


function Modal( {children} ) {
    const style = {
        position: 'fixed',
        top : 0,
        left : 0,
        right : 0,
        bottom : 0,
        backgroundColor : 'rgba(0,0,0,0.5)',
        display : 'flex',
        alignItems : 'center', 
        justifyContent : 'center'
    }

    const style2 = {
        backgroundColor: 'white',
        padding : '20px',
        borderRadius : '20px'
    }

    return createPortal(
        <div style={style}>
            <div style={style2}>{children}</div>
        </div>,
        document.body
    );
}

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

    return (
        <div>
            <h1>React Portal Example</h1>
            <button onClick={ () => setOpen(true) }> open modal </button>
            
            { open && (
                    <Modal>
                        <h2>์•ˆ๋…•ํ•˜์„ธ์š”</h2>
                        <button onClick={ () => setOpen(false) } >๋‹ซ๊ธฐ</button>
                    </Modal>
                )

            }
        </div>
    );
}

createRoot(document.getElementById('mainModal')).render(
    <App />
);

 

 

 

 

๐Ÿ“ React Suspense

  • ์ฝ”๋“œ๋‚˜ ๋ฐ์ดํ„ฐ๊ฐ€ ๋กœ๋“œ๋  ๋•Œ๊นŒ์ง€ ๋Œ€์ฒด HTML์„ ํ‘œ์‹œํ•˜๋Š” ๊ธฐ๋Šฅ
  • ์•„์ง ๋กœ๋”ฉ์ด ์•ˆ๋˜๋ฉด,,, ๋กœ๋”ฉ ๋˜๊ธฐ ์ „๊นŒ์ง€์˜ LOADING... ๊ฐ™์€ ๊ฑธ ํ‘œ์‹œํ•ด์ฃผ๊ธฐ ์œ„ํ•จ.
  • React.lazy๋Š” ๋ฐ˜๋“œ์‹œ import()์™€ ํ•จ๊ป˜ ์จ์•ผ ํ•œ๋‹ค.
import { createRoot } from 'react-dom/client';
import React, { Suspense } from 'react';


// const LazyGreeting = React.lazy( () => import('./Greeting') );
const LazyGreeting = React.lazy( () => 
    new Promise((resolve) => {
        setTimeout( () => resolve(import('./Greeting')), 2000 );
    })
);


function App() {
    return (
        <div>
            <Suspense fallback={<div>Loading...</div>}>
                <LazyGreeting />
            </Suspense>
        </div>
    );
}

createRoot(document.getElementById('suspense')).render(
    <App />
);

 

## Greating.jsx

function Greeting() {
    return <h1>์•ˆ๋…•ํ•˜์„ธ์š”??</h1>
}

export default Greeting;

์ถœ์ฒ˜ : 

 

 

 


๊ฐœ๋ฐœ ๊ณต๋ถ€๋ฅผ ์œ„ํ•œ ๋ธ”๋กœ๊ทธ ์ž…๋‹ˆ๋‹ค. 

์˜ค๋ฅ˜๊ฐ€ ์žˆ๋‹ค๋ฉด ๋Œ“๊ธ€๋กœ ์•Œ๋ ค์ฃผ์„ธ์š”! 

๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค.

728x90