PleaseNoBugs
PleaseNoBugs

Reputation: 179

React include dynamic prop value in component name

I am trying to render a react component. The first part of the component will remain the same, however the second part needs to change dynamically based on the data returned from the props. Is there some way to concatenate these together?

import * as Icon from 'react-cryptocoins';

class ResultRow extends PureComponent {
  render() {
    return (
      <div className="component-result-row">

        <Icon.{this.props.name}/>
      </div>
    );}}

Hardcoding the name works as expected

<{Icon.image1}/>

Solution:

import * as Icon from 'react-cryptocoins';

class ResultRow extends PureComponent {
  var name = this.props.name;
  var Component = Icon[symbol];
  render() {
    return (
      <div className="component-result-row">

       <Component/>
  </div>
);}}

Upvotes: 2

Views: 877

Answers (1)

Mayank Shukla
Mayank Shukla

Reputation: 104529

One possible way is store the value in a variable (should start with capital letter) then render that.

Like this:

class ResultRow extends PureComponent {
  render() {

    const Comp = Icon[this.props.name];

    return (
      <div className="component-result-row">
        <Comp />
      </div>
    );
}}

Upvotes: 3

Related Questions