반응형
Add and remove effects within React.
The button that toggles mounting of a child component, WindowEvent.
When the WindowEvent component is active, add an event listener to the window that triggers an alert if the user double-clicks on the page.
Make sure to remove the window event when the component is toggled off.
WindowEvent.js
import { useEffect } from "react"
export default function WindowEvent() {
useEffect(() => {
const doubleClick = () => alert('mouse double clicked')
window.addEventListener('dblclick', doubleClick)
return () => window.removeEventListener('dblclick', doubleClick)
}, [])
return (
<h2>Window event active</h2>
)
}
ToggleWindowEvent.js
import { useState } from 'react'
import WindowEvent from './WindowEvent'
export default function ToggleWindowEvent () {
const [windowEvent, setWindowEvent] = useState(false)
return (
<div>
<button onClick={() => setWindowEvent(prevState => !prevState)}>Toggle Window Event</button>
{windowEvent && <WindowEvent />}
</div>
)
}
App.js
import ToggleWindowEvent from './ToggleWindowEvent'
function App () {
return (
<div className='App'>
<ToggleWindowEvent />
</div>
)
}
export default App
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
결과 화면
반응형
'PROGRAMING > React' 카테고리의 다른 글
[REACT] Pixel art - React Context (0) | 2024.03.07 |
---|---|
[REACT] Color picker (0) | 2024.03.07 |
[REACT] Score Keeper - localStorage (0) | 2024.03.06 |
[REACT] Dog Picture - API (0) | 2024.03.06 |
[REACT] Form Validator (0) | 2024.03.06 |