5

Dynamic import base on props name in react

import { a, b, c } from 'some-package/theme' // should not import everything here

const MyComp = ({ theme, ...other }) => { 

  console.log(theme) //can be a, b, c, d, e etc
  return(<MyCompInner />) 
}

export default MyComp

How can I do dynamic import from 'some-package/theme' ? the prop of theme can be a, b, c and more. Theme props is the option, but I have to import the value from 'some-package/theme' before I supply it to <MyCompInner />

1 Answer 1

4

You could use require() for this. Unlike import which has to be at the top, you can use require() anywhere in your code.

const MyComp = ({ theme, ...other }) => { 

  const t = require('some-package/theme/' + theme);
  return(<MyCompInner theme={t} />) 
}

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

3 Comments

can't do import here? why require would work? Is that a apart of jsx?
@Melissa92, not entirely sure, but probably some kind of restriction in the bundling process.
yeah thanks so much for this!! Although enyzme test won't let that to work.

Your Answer

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