screen_rotation
Copied to Clipboard
<!DOCTYPE html> <html> <head> <meta charset="UTF-8" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.min.js"></script> </head> <body> <div id="app"></div> <script type="text/babel"> const { useRef } = React; const App = () => { const divRef = useRef(null); const handleClick = () => { // Get the current background color directly from the DOM element const currentColor = divRef.current.style.backgroundColor; const newColor = currentColor === 'white' ? 'lightblue' : 'white'; divRef.current.style.backgroundColor = newColor; }; return ( <div className='container'> <h3>React Js Get Element by Ref </h3> <div ref={divRef} onClick={handleClick} style={{ padding: '20px', cursor: 'pointer', backgroundColor: 'white' }} > Click me to change my background color </div> </div> ); } ReactDOM.render(<App />, document.getElementById('app')); </script> <style> .container { border-radius: 8px; box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1); padding: 20px; margin: 20px auto; max-width: 600px; text-align: center; } </style> </body> </html>