简体   繁体   中英

React - dynamic use of country-flag-icons library

We are using https://www.npmjs.com/package/country-flag-icons library that allows to use flags icon in React in this way:

import Flags from 'country-flag-icons/react/3x2'

<Flags.US title="United States" className="..."/>

But how can i use it dynamically? Because the State code is returned through services.

I mean a some solution like this:

<Flags.{myVar} title="United States" className="..."/>

EDIT This is my file:

import { Link } from "react-router-dom";
import Flags from "country-flag-icons/react/3x2";

const Person = ({ linkDetail, flagNationCode }) => (
  <Link to={linkDetail}>
   
    <div className="person-footer">
      <div className="info">
        <div className="label">{flagNationCode}</div>
        <div className="value">
            <Flags.US />
          )}
        </div>
      </div>
    </div>
  </Link>
);

export default Person;

You need to pick out the component into a variable that starts with a capital letter and use that as the component, eg:

const Person = ({ linkDetail, flagNationCode }) => {
  const Flag = Flags[flagNationCode];

  return (
    <Link to={linkDetail}>
      <div className="person-footer">
        <div className="info">
          <div className="label">{flagNationCode}</div>
          <div className="value">
            <Flag />
          </div>
        </div>
      </div>
    </Link>
  );
};

You can pull out the Flag you want in to a variable and then use it as a Component

import { Link } from "react-router-dom";
import Flags from "country-flag-icons/react/3x2";

const Person = ({ linkDetail, flagNationCode }) => {
const Flag = Flags[flagNationCode];
return (
  <Link to={linkDetail}>
    <div className="person-footer">
      <div className="info">
        <div className="label">{flagNationCode}</div>
        <div className="value">
            <Flag />
        </div>
      </div>
    </div>
  </Link>
)};

export default Person;

For anyone having the problem: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type

Try this

import { Link } from "react-router-dom";
import Flags from "country-flag-icons/react/3x2";

const Person = ({ linkDetail, flagNationCode }) => {

const obj: Record<string, FlagComponent> = Flags;
const Flag = Flags[flagNationCode];
return (
  <Link to={linkDetail}>
    <div className="person-footer">
      <div className="info">
        <div className="label">{flagNationCode}</div>
        <div className="value">
            <Flag />
        </div>
      </div>
    </div>
  </Link>
)};

export default Person;

adding this conversion const obj: Record<string, FlagComponent> = Flags; worked for me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM