Nachtfunke
Nachtfunke

Reputation: 367

Correct type to set for a renderAs Propery in Typescript React Components?

Components sometimes need to be able to render as a different HTML element, depending on its context. For example, this Card component.

import React from 'react';

export type Props = {
    className?: string,
    renderAs: any
}

export const Card: React.FC<Props> = function Card({ renderAs, className, children }) {
    const Element = renderAs;
    return (
        <Element className={`card  ${ className ? className:'' }`}>
            { children }
        </Element>
    )
}

When actually using the component, all works as it is supposed to:

<Card renderAs="section">...</Card>
<Card renderAs="div">...</Card>

But I am not sure, if using renderAs: any is the correct type, for this use case and I would appreciate some insight on this!

Thank you in advance!

Upvotes: 0

Views: 729

Answers (1)

gqstav
gqstav

Reputation: 2082

The actual type you are passing is React.ElementType, leaving

export type Props = {
    className?: string,
    renderAs: React.ElementType
}

What you say by this is that you want to enable renderAs to be set to some intrinsic JSX element such as section, div, span ...

Upvotes: 1

Related Questions