How to globally disable/hide/replace a component by name in React?

1.6k Views Asked by At

I have a large React app and I have a few components that I would like to completely disable from a config or global level. Is there any kind of global hook that I can use that is called before any component is rendered? If so, I imagine I can check the name of the component and return null if the name is on the disabled list. How would you do this?

3

There are 3 best solutions below

2
On

There are many ways to do this, so, I'll just describe one simple way: using references and updating the states accordingly.

Full working feature hide/showing sandbox online: codesandbox.io ReactJS Feature Hide/Show Demo

Defined are two classes, class Feature extends React.Component and class App extends React.Component. The render() for <Feature/> is...

  render() {
    if (!this.state.enabled) {
      return <div />;
    }
    return (
      <div className="Feature">
        <h1>My Feature!</h1>
      </div>
    );
  }

And the option for enabling/disabling a feature in <App /> would handle display/hiding like so...

  handleOnClick(e) {
    if (e.target.checked) {
      this.feature.setState({ enabled: true });
    } else {
      this.feature.setState({ enabled: false });
    }
  }

Of course, you need to make sure that <Feature /> has the reference set...

    <Feature
      ref={instance => {
        this.feature = instance;
      }}
    />
0
On

There are a lot of ways to do this:

React's Context API allows you pass props through every level of the component tree so you can use them as flags to enable/disable components. Should be used sparingly however.

Higher Order Components are basically just functions that return a component. You could wrap your components in logic to render them as needed.

Or of course you could use a global state manager like redux to set global states.

2
On
  1. If you need simplest solution just use browser global vars and check it in render.

    render() { if( window.globalFlag ) return null return ( <div> feature content...

    Drawbacks:

    • modifying component,
    • using global scope,
    • some unnecessary code can be run earlier (f.e. constructor) and later (f.e. componentDidMount).
  2. Use HOCs - wrap your component - connecting with global store using redux or context API.

    <FlagsProvider store={flagStore}> <SomeComponent_1> <SomeComponent_2> <FlagsConsumer flag="someFeatureFlag"> <SomeFeatureComponent />

    <FlagsConsumer/> connects to store (redux connect would be an inner wrapper - composing HOCs) and conditionally renders <SomeFeatureComponent /> (or null).

    Of course HOC can pass received props to wrapped component - it can be functionally transparent.

  3. Don't reinvent the wheel - use some ready module, read tutorials, google for sth suitable.

HOC can also play a role of A/B testing.