Home > Back-end >  Dynamically paste value in dot notation in react component
Dynamically paste value in dot notation in react component

Time:11-28

I'm trying to use the React-NBA-Logos package(npm link) in a small project and faced a question. According to the documentation here is an example of this package use

import React from 'react';
import * as NBAIcons from 'react-nba-logos';

const Example = () => {
  return <NBAIcons.TOR />; // Loads the Toronto Raptors logo
};

export default Example;

The question is it possible to paste a variable with a dynamic string value(with some correct tripcode) here? Something like this

const Example = () => {
  const NEW_VAR = 'NYK';
  return <NBAIcons.NEW_VAR />;
};

CodePudding user response:

You can get around this by creating an alias for the component.

const Example = () => {
  const NEW_VAR = 'NYK';
  const Component = NBAIcons[NEW_VAR];
  return <Component />;
};

CodePudding user response:

A functional approach would work well here:

function NBAIcon (name, props = {}) {
  const Icon = NBAIcons[name];
  return <Icon {...props} />;
}

function Example () {
  return (
    <ul>
      <li>{NBAIcon('TOR')}</li>
      <li>{NBAIcon('ATL', {size: '64px'})}</li>
    </ul>
  );
}
  • Related