Skip to content
Advertisement

How to render icon based on props using react and typescript?

I’m using react-feather to render icons in a component. I’m able to get it to import a static icon by hard coding it in. But how do I make it render the icon based on what has been passed to it in the IconLeft.icon props?

import { Camera } from 'react-feather';
import React, { FunctionComponent } from 'react';

type HeaderProps = {
    title: string;
    iconLeft?: {
        icon?: string;
        url?: string;
        state?: string;
        label?: string;
    }
}

export const DefaultHeader: FunctionComponent<HeaderProps> = ({ title, iconLeft, iconRight}) => <header>
    <h1>{String}</h1>
    <Camera size={24} stroke-width={2}/>
</header>

Advertisement

Answer

You can use cloneElement to dynamically render any component you want by passing it as a prop.

import React, { cloneElement, FunctionComponent } from "react";

type HeaderProps = {
    title: string;
    iconLeft?: {
        icon: JSX.Element;
        url?: string;
        state?: string;
        label?: string;
    };
};

export const DefaultHeader: FunctionComponent<HeaderProps> = ({
    title,
    iconLeft,
}) => (
    <header>
        <h1>{String}</h1>
        {iconLeft && cloneElement(iconLeft.icon, { size: 24, "stroke-width": 2 })}
    </header>
);

Usage example:

<DefaultHeader iconLeft={{ icon: <Camera /> }} />
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement