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
- Filtering array of child components
- React Module parse failed: Unexpected character '@'
- React Hooks + Mobx => Invalid hook call. Hooks can only be called inside of the body of a function component
- React: Avoid nondeterministic first render (hack with "mounted" state)
- How to update state in better way
- Uncaught TypeError: Cannot read properties of undefined (reading 'user')
- error in react " Attempted import error: 'TodoItem' is not exported from './Todoitem'. "
- React how to create a data for chart?
- React Router serverside rendering errors: Warning: Failed propType: Required prop `history` was not specified in `RoutingContext`
- Creating custom Input type file button in React
- how to get the data from a component within a form in react
- Simple Website that Shows Reactjs + Redux
- How do I forward a cookie using fetch in getServerSideProps?
- Invariant Violation: Text strings must be rendered within a Text component
- Material UI Grid not working properly with Paper Component for nested Grid
- Using an async function on useEffect that has as an argument a State that's also async setted
- How to access the below json value
- React components as plain JS objects?
- How to toggle checkbox value in React Hooks?
- Hook's useState initial value never changes in callback that is memoized
- Collapse from react-bootsrap doesn't work
- How to dynamically render JSX component X times?
- Compare current to previous when mapping array of objects onto html elements
- Using two redux actions when clicking a button
- Replace multiple parts of a string with anchor tag
- Why is type SFC<AnchorProps> not assignable to type SFC<{}>?
- Remove duplicates from inner array of array of objects
- 'Parsing error: Unexpected token' error for an arrow function?
- Why is my setState not updating the state or triggering re-render?
- State value `undefined` on state onChange