screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://unpkg.com/react@17.0.2/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.development.js"></script> <script src="https://cdn.jsdelivr.net/npm/@babel/standalone@7.14.6/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel" data-presets="env,react"> const { useState, useEffect, useRef } = React; function App() { const buttonRef = useRef(null); useEffect(() => { const handleClick = () => { alert("Button clicked"); }; const buttonEl = buttonRef.current; buttonEl.addEventListener("click", handleClick); return () => { buttonEl.removeEventListener("click", handleClick); }; }, []); return ( <div className='container'> <h3>React Js add event listener to ref</h3> <button ref={buttonRef}>Click me</button> </div> ); } ReactDOM.render(<App />, document.getElementById("app")); </script> <style> .container { max-width: 500px; margin: 0 auto; padding: 20px; background-color: #f2f2f2; border-radius: 5px; } h3 { margin-top: 0; } .click-button { display: inline-block; padding: 10px 20px; background-color: #4caf50; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; transition: background-color 0.3s ease; } .click-button:hover { background-color: #45a049; } .click-button:active { background-color: #3e8e41; } </style> </body> </html>