0
votes

From a headless CMS I'm fetching the list of components which should be included on certain page. Once fetched, I dynamically import mentioned components like this:

const components = ["Test", "Test2"]; // comes from CMS

const DynamicComponent = ({ name }) => {
   let Component;
   Component = require(`./components/${name}`).default;
   return <Component />;
};

export default function App() {
   return (
      <Container>
         {components.map((comp, i) => (
         <DynamicComponent name={comp} key={i} />
          ))}
      </Container>
   );
}

And then I just pass these component as children props to some container.

However, although everything works fine, I'm getting some warning for every component I have that says:

The component styled.div with the id of "sc-bdnylx" has been created dynamically. You may see this warning because you've called styled inside another component. To resolve this only create new StyledComponents outside of any render method and function component.

I googled the warning but everywhere the solution is to not define styles within the component. I could be wrong, but I don't think that's applicable here.

Here's the full example: https://codesandbox.io/s/style-components-dynamic-5id3y?file=/src/App.js (check the console output)

How can I get rid of this warning?

Thank you

1

1 Answers

0
votes

Well, the warning is pretty clear when it says "create new StyledComponents outside of any render method and function component". So what you can do is refactor your functional component DynamicComponent into a class based component

class DynamicComponent extends React.Component {
  constructor(props) {
    super(props);
    this.Component = require(`./components/${this.props.name}`).default;
  }
  render() {
    return <this.Component />;
  }
};

EDIT: tested on your sandbox, made the fixes to my previous code, and your warnings are gone