Umur Gedik
Umur Gedik

Reputation: 507

In react.js is there any way to disable all children events

I want to build an application which has two states; pause and active. For example I want to disable all children/owned components' events like onClick, onChange, onKeyDown, .etc.

I had thought to give isActive=false prop through all it's children/owned components and check for the property isActive on event handlers. If isActive property is falsy event handler will do nothing. I can make this mechanism even easier with a simple helper function. But my concern is when I changed the app state to paused, all children components needs to be re-rendered.

Im searching for a way to bypass all event handlers (not custom ones) without re render all components.

UPDATE: I watch rendering rectangles on chrome end it doesn't re render the children. But if there any better reacty way to do this I want to learn it.

Upvotes: 3

Views: 5947

Answers (2)

mrmicrowaveoven
mrmicrowaveoven

Reputation: 185

Set pointerEvents='none' in the styling of the container div. It'll disable all of the children. I know it from React Native, but it seems to work in React.js as well.

Upvotes: -1

Brigand
Brigand

Reputation: 86240

One way to solve this is using a simple guard abstraction. It works like this:

var sayHi = guard("enabled", function(){
  alert("hi");
});

guard.deactivate("enabled");
sayHi(); // nothing happens
guard.activate("enabled");
sayHi(); // shows the alert

Using this for event handlers is similar:

handleChange: guard("something", function(e){
  // if 'something' is deactivated, the input won't change
  this.setState({value: e.target.value});
})

// or

return <div onClick={guard("something", this.handleClick)}>click me!</div>

Here's an implementation of guard

var guard = function(key, fn){
  return function(){
    if (guard.flags[key]) {
      return fn.apply(this, arguments);    
    } 
  };
};

guard.flags = {};
guard.activate = function(key){ guard.flags[key] = true };
guard.deactivate = function(key){ guard.flags[key] = false };

Upvotes: 7

Related Questions