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?
How to globally disable/hide/replace a component by name in React?
1.5k Views Asked by Byron Sommardahl AtThere are 3 best solutions below

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.

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
).
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.
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.
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
andclass App extends React.Component
. Therender()
for<Feature/>
is...And the option for enabling/disabling a feature in
<App />
would handle display/hiding like so...Of course, you need to make sure that
<Feature />
has the reference set...