2
import React, { Component } from 'react';    

let SomeComp;
if (process.env.REACT_APP_V === '1') {
  SomeComp = import('../section/SomeComp');
}

Class App

...

render() {
  return {
    {this.state.version === '1' && <SomeComp />}
  }
}

I want to import the SomeComp component conditionally.

Is this the correct way?

The error I'm getting is:

Warning: React.createElement: type is invalid -- expected a string (for built-in components) 

If I do a normal

import SomeComp from '../section/SomeComp'; 

it works. So it's no issue with the export from SomeComp

Any ideas?

2
  • I would avoid this if you can. Can't you pass in the component to the component? In any case, the problem here is that dynamic import() is async (it returns a promise) so you cannot render it until it's loaded. Commented May 7, 2019 at 21:51
  • I see. It's a css issue so I can condionally import the css file instead. Commented May 7, 2019 at 22:08

2 Answers 2

1

Try this:

    const SomeComp = React.lazy(() => import('./SomeComp'));

    Class App
    render() {
      return {
        <Suspense fallback={<div>Loading...</div>}>
         {this.state.version === '1' && <SomeComp />}
        </Suspense>
      }

    }

You will run into issues if you are using a back end server. The suspense should wrap the relevant code that is loaded on demand. You might also want to look into this neat little npm here (react loadable)

Sign up to request clarification or add additional context in comments.

1 Comment

I get "Add a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display."
0

You can use a ternary statement, like an if/else statement. So in this case if version = 1, the component will render:

{(this.state.version === '1') ? <SomeComp />
: null
}

3 Comments

Why use ternary over logical operator? what is the benefit of returning null here?
@Kleo If you don't want the component to render at all if the requirement is not met you can return an empty div or null.
First of all, returning an empty div is bad practice. No reason to overload the DOM with an empty div. Second of all, unless you will be doing something with null, you should be using && operator. Logical over ternary always if what you are trying to achieve is simply render or not render.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.