Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blacklist React components

Is there a way to define a function to hook before each component in my app is mounted?

The idea is that if a component is blacklisted it doesn't mount at all.

The solution must leave the components unmodified for backward compatibility and should run in production (so rewire and other testing tools are probably off the table but open to suggestions :) )

Example

//something like this...
ReactDOM.beforeEachComponentMount( (component, action) => {
    if(isBlacklisted(component)){
        action.cancelMountComponent();
    }
}
like image 782
snovelli Avatar asked Mar 04 '18 11:03

snovelli


3 Answers

Could you write a simple Babel plugin that transforms blacklisted components to a noop functional component () => {} at compile time?

like image 125
Jed Richards Avatar answered Sep 20 '22 01:09

Jed Richards


You could wrap the required components inside a higher order component that checks whether the component is blacklisted or not.

for example :

class YourComponent extends Component {   
 constructor(props){
  super(props);
 }

 render(){
  return(
    // your component goes here .. 
  );
  }
}
export default WithPermission(YourComponent);

check if the component needs to be rendered or not inside the HOC WithPermission.

function withPermission(YourComponent) {
  class WithPermission extends React.Component {
   constructor(props) {
     super(props);
   }

// you can check the props inside ComponentDidMount and set a flag if 
// the component satisfies the criteria for rendering.

 render() {
  const {blacklistedComponents,...rest} = this.props;
   if(!blackListedComponents){
    return <YourComponent {...rest} />
   }
   else{
    return null;
   }
  }
 }
}
like image 45
Vishnu Avatar answered Sep 23 '22 01:09

Vishnu


There is no such functionality out of box.

You may shim React rendering cycle, I mean shim React.createElement method and validate component before it is added to VDOM

All JSX is processed through React.createElement

e.g. at the start of app add

let React = require('react');
let originalCreateElement = React.createElement;
React.createElement = function() {
    let componentConstructorOrStringTagName = arguments[0];
    if (isBlacklisted(componentConstructorOrStringTagName)) {
        return null;
    }
    return originalCreateElement.apply(this, arguments);
}
like image 34
Andrii Muzalevskyi Avatar answered Sep 20 '22 01:09

Andrii Muzalevskyi