Abanob Akram
Abanob Akram

Reputation: 23

Conditional Component Import ReactJS

I'm currently building a ReactJS project that has free/pro versions. In the free version, I need to import a component conditionally when it exists. The component file exists only when the pro version is installed (pro version folder exists).

I tried to use lazy and Suspense to achieve this, but the compiler throws an error that "no such file or directory" when the pro version is not installed because the component file doesn't exist in this case.

getPROComponent() {
      const ProComponent = lazy(() => import('./ProComponent'))
      return (
          <Suspense fallback={<div></div>}>
              <ProComponent label={this.state.label} checked={this.state.checked} onCheck={this.onCheck} />
          </Suspense>

      );
}

render() {
    const { isPRO } = this.state
    
    return (
        ! isPRO ? <h1>Free Version</h1> : this.getPROComponent
    )
}

Is there any way I can achieve this?

Upvotes: 0

Views: 231

Answers (1)

Joel&#39;-&#39;
Joel&#39;-&#39;

Reputation: 734

  • Use lazy loading for the component (or module). Always generate it as part of your build.
  • Use a config file to hide or show the component.
  • Delete the chunk which contains the pro stuff after the build completed

Upvotes: 1

Related Questions