score:98
If you need to handle DOM events not already provided by React you have to add DOM listeners after the component is mounted:
Update: Between React 13, 14, and 15 changes were made to the API that affect my answer. Below is the latest way using React 15 and ES7. See answer history for older versions.
class MovieItem extends React.Component {
componentDidMount() {
// When the component is mounted, add your DOM listener to the "nv" elem.
// (The "nv" elem is assigned in the render function.)
this.nv.addEventListener("nv-enter", this.handleNvEnter);
}
componentWillUnmount() {
// Make sure to remove the DOM listener when the component is unmounted.
this.nv.removeEventListener("nv-enter", this.handleNvEnter);
}
// Use a class arrow function (ES7) for the handler. In ES6 you could bind()
// a handler in the constructor.
handleNvEnter = (event) => {
console.log("Nv Enter:", event);
}
render() {
// Here we render a single <div> and toggle the "aria-nv-el-current" attribute
// using the attribute spread operator. This way only a single <div>
// is ever mounted and we don't have to worry about adding/removing
// a DOM listener every time the current index changes. The attrs
// are "spread" onto the <div> in the render function: {...attrs}
const attrs = this.props.index === 0 ? {"aria-nv-el-current": true} : {};
// Finally, render the div using a "ref" callback which assigns the mounted
// elem to a class property "nv" used to add the DOM listener to.
return (
<div ref={elem => this.nv = elem} aria-nv-el {...attrs} className="menu_item nv-default">
...
</div>
);
}
}
score:2
I recommend using React.createRef()
and ref=this.elementRef
to get the DOM element reference instead of ReactDOM.findDOMNode(this)
. This way you can get the reference to the DOM element as an instance variable.
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class MenuItem extends Component {
constructor(props) {
super(props);
this.elementRef = React.createRef();
}
handleNVFocus = event => {
console.log('Focused: ' + this.props.menuItem.caption.toUpperCase());
}
componentDidMount() {
this.elementRef.addEventListener('nv-focus', this.handleNVFocus);
}
componentWillUnmount() {
this.elementRef.removeEventListener('nv-focus', this.handleNVFocus);
}
render() {
return (
<element ref={this.elementRef} />
)
}
}
export default MenuItem;
score:2
Here is a dannyjolie
more detailed answer without need of component reference but using document.body
reference.
First somewhere in your app, there is a component method that will create a new custom event and send it. For example, your customer switch lang. In this case, you can attach to the document body a new event :
setLang(newLang) {
// lang business logic here
// then throw a new custom event attached to the body :
document.body.dispatchEvent(new CustomEvent("my-set-lang", {detail: { newLang }}));
}
Once that done, you have another component that will need to listen to the lang switch event. For example, your customer is on a given product, and you will refresh the product having new lang as argument.
First add/remove event listener for your target component :
componentDidMount() {
document.body.addEventListener('my-set-lang', this.handleLangChange.bind(this));
}
componentWillUnmount() {
document.body.removeEventListener('my-set-lang', this.handleLangChange.bind(this));
}
then define your component my-set-langw
handler
handleLangChange(event) {
console.log("lang has changed to", event.detail.newLang);
// your business logic here .. this.setState({...});
}
score:4
First off, custom events don't play well with React components natively. So you cant just say <div onMyCustomEvent={something}>
in the render function, and have to think around the problem.
Secondly, after taking a peek at the documentation for the library you're using, the event is actually fired on document.body
, so even if it did work, your event handler would never trigger.
Instead, inside componentDidMount
somewhere in your application, you can listen to nv-enter by adding
document.body.addEventListener('nv-enter', function (event) {
// logic
});
Then, inside the callback function, hit a function that changes the state of the component, or whatever you want to do.
score:21
You could use componentDidMount and componentWillUnmount methods:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class MovieItem extends Component
{
_handleNVEvent = event => {
...
};
componentDidMount() {
ReactDOM.findDOMNode(this).addEventListener('nv-event', this._handleNVEvent);
}
componentWillUnmount() {
ReactDOM.findDOMNode(this).removeEventListener('nv-event', this._handleNVEvent);
}
[...]
}
export default MovieItem;
Source: stackoverflow.com
Related Query
- ReactJS - Add custom event listener to component
- Is there a way to add onClick event to a custom component
- Add an event to a Stateless Component in ReactJS
- How do you add an keyup event listener to window in a React functional component that only gets added when the app originally loads?
- How can I add styling to an event listener in an class component in React?
- Is there any way to add an event listener in a method in a component A, and have the target in a separate component
- ReactJS fire an event into component when my global socket listener fires through socket
- How to add a 'mousemove' event listener to a component Cursor which is moved with the cursor pointer in ReactJS?
- How can I add an event listener to the ReactJS Material-UI autocomplete clear button?
- How to add event listener to a component and remove it when the user click anywhere else in the window?
- reactjs event listener beforeunload added but not removed
- How to add scroll event in react component
- React navigation didfocus event listener works differently between class component and functional component
- Custom component topbar button event RNN v2
- How to add event listener to a ref?
- How to add Event in React Functional Component
- how to add event listener to cookie so that to notify when a cookie gets updated or expired
- How can I create a custom Event Component for react-big-calendar?
- How to add an event listener to useRef in useEffect
- Custom ReactJS component that respects 'valueLink'
- onDeviceReady event listener in react component
- Is it too expensive to add and remove event listeners on every call of my React custom hook? How to avoid it?
- ReactJS Ant design select component mock change event
- React: How to add onChange functionality inside of Function component using React Hooks? Need onClick event from a checkbox to influence input state
- Which one has better performance: add and remove event listener on every render VS running an useEffect to update a ref
- Creating a Custom Button in React Typescript and add onClick Event
- unable add required attribute to a ReactJS input component
- How to add custom indicator in trading view Charting library in reactjs
- Add styles to Styled Component custom Component in React Native
- How can I remove event Listener so it would not try to update state when component is unmounted?
More Query from same tag
- Get the data from an object
- Can I create a prop that inherits another prop's generic type?
- Open popup on DataTable row click in ReactJS
- Correct way to create event handlers using hooks in React?
- Testing useEffect unmount callback called using acts in enzyme
- React Router & Express Conflicts
- React escaping vars inside an element
- Remove items form the list in React js
- onClick event won't work in my React code
- Google Analytics 4 with React
- Array only has data inside event handler
- Stripe redirectToCheckout - "TypeError: stripe.redirectToCheckout is not a function"
- Don't highlight the cells when close dialog in react?
- Why is child component re-rendering if only prop has useCallback?
- Why does this code does not show buttons on different lines instead of side-by-side?
- Why do I encounter: "TypeError: t(...).isPlaceholder is not a function" when "import './bootstrap/dist/css/bootstrap.min.css'"
- React slider not rendering correctly
- How to clear the text field in formsy material ui React
- Cannot read property 'state' of null
- Typescript error after update of react and react-dom
- Create Gatsby Project on a git initialized folder
- Change form.item label font size in AntD
- List of Students Click and Redirect to page React
- How can I return a file using react? Or `npm unload` analogs for express
- Losing Context upon page refresh
- React-native view auto width by text inside
- How to cast an HTMLElement to a React element?
- Generating JSON translation files
- importing googleapis in Nodejs gives error. How to properly import googleapis pakage.Iam using type:modules
- PNPM - Starting new project not working as expected