React: rendering a concatenated component based on an imported component list

I'm not sure that what I'm trying to do is even possible, or if there is a better way to achieve my goal. Any insight would be very helpful.

Context:

  • I have a catalog full of components that display embedded SVG
  • These components are collected in a file IconsIndex.jsand exported as such:

export { default as Rocket } from "./Rocket";

  • I import an index to access my icon library from any given component:

import * as Icon from "./icons/IconsIndex";

This allows me essentially: <Icon.Rocket />which renders the SVG component perfectly.

I would like the component <Icon />to be more dynamic of the parent components.

For instance:

class ResourceBlock extends React.Component {
  render() {
    return (
      <BlockContainer>
        <BlockIcon>
          <Icon.Rocket />
        </BlockIcon>
        <BlockTitle>{this.props.caption}</BlockTitle>
        <Button>{this.props.buttonText}</Button>
      </BlockContainer>
    );
  }
}

Rocket , ResourceBlock. , , - :

<ResourceBlock icon={Icon.Rocket} caption="Lorem..." buttonText="..." />

? ?

, SVG , , <Icon /> .

+4
2

:

<ResourceBlock icon={<Icon.Rocket />} caption="Lorem..." buttonText="..." />

class ResourceBlock extends React.Component {
  render() {
    return (
      <BlockContainer>
        <BlockIcon>
          {this.props.icon}
        </BlockIcon>
        <BlockTitle>{this.props.caption}</BlockTitle>
        <Button>{this.props.buttonText}</Button>
      </BlockContainer>
    );
  }
}
+1

, JSX, node , html-, . local const :

class ResourceBlock extends React.Component {
  render() {
    const Icon = this.props.icon;
    return (
      <BlockContainer>
        <BlockIcon>
          <Icon />
        </BlockIcon>
        <BlockTitle>{this.props.caption}</BlockTitle>
        <Button>{this.props.buttonText}</Button>
      </BlockContainer>
    );
  }
}

, :

<ResourceBlock icon={Icon.Rocket} caption="Lorem..." buttonText="..." />
+3

Source: https://habr.com/ru/post/1690277/


All Articles