Home > front end >  JSX string interpolation into a component name
JSX string interpolation into a component name

Time:11-18

I have this code...

import React from 'react';
import Fade from 'react-reveal/Fade';
import { Novice } from '../../../Icons/Novice';
import { Apprentice } from '../../../Icons/Apprentice';
import { Explorer } from '../../../Icons/Explorer';
import { Advocate } from '../../../Icons/Advocate';
import { Profesional } from '../../../Icons/Profesional';
import { Ambassador } from '../../../Icons/Ambassador';

export const ProfileType = (props) => {
  const {
    label = 'Apprentice',
  } = props;
  return (
    <Fade top delay={2100}>
      <div className="profile-card__work-type">
        {
        /* {label === 'Novice' && <Novice />}
        {label === 'Apprentice' && <Apprentice />}
        {label === 'Explorer' && <Explorer />}
        {label === 'Advocate' && <Advocate />}
        {label === 'Profesional' && <Profesional />}
        {label === 'Ambassador' && <Ambassador />} */
        }
        { `< ${label} />` }
        <span className="profile-card__work-type-text">
          {' '}
          {label}
        </span>
      </div>
    </Fade>
  );
};

I want to use the 'label' variable as the name of my component and I'm trying to use string interpolation to use it like this { `< ${label} />` } but it just prints out the string < Novice/> to screen.

enter image description here

How can use the label varible as the name of the component instead of the several lines of conditionals?

Best wishes, Nicolas

CodePudding user response:

Use an object to store your components...

const obj = {
  Novice: <Novice />,
  Apprentice: <Apprentice />,
  Explorer: <Explorer />,
  Advocate: <Advocate />,
  Profesional: <Profesional />,
  Ambassador: <Ambassador />
};

And then access the object using the label.

{obj[label]}

CodePudding user response:

You can't just put < ${label} /> and expect it to be evaluated as a Component if your really want to do this you have to use the dangerouslySetInnerHTML prop on a <div/> or something and give it a valid html String. But as the name of the prop suggests its dangerous given the possibility of remote code execution attacks.

Another way of going about this and probably the best way, like the other Answer suggests is putting your Components already in an Array or as properties of an Object and accessing them through the index of the Component in the Array or the key of the Object property.

  • Related