Source Code:
(back to article)
Submit
Result:
Report an issue
<body> <div id="root"></div> <!-- React and ReactDOM CDN links --> <script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script> <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script> <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script> <script type="text/babel"> const { useRef, useEffect } = React; const CustomCard = ({ title, children }) => { const cardRef = useRef(null); useEffect(() => { if (cardRef.current) { const shadowRoot = cardRef.current.attachShadow({ mode: 'open' }); shadowRoot.innerHTML = ` <style> .card { padding: 10px; border: 1px solid #ddd; border-radius: 5px; box-shadow: 0 2px 5px rgba(0,0,0,0.2); } .card-title { font-size: 1.2em; margin-bottom: 5px; } </style> <div class="card"> <div class="card-title">${title}</div> <div class="card-content">${children}</div> </div> `; } }, [title, children]); return <div ref={cardRef}></div>; }; const App = () => ( <CustomCard title="Hello World"> This is content inside the shadow DOM. </CustomCard> ); const rootElement = document.getElementById('root'); const root = ReactDOM.createRoot(rootElement); root.render(<App />); </script> </body>