Zhiguo Jiang
Zhiguo Jiang

Reputation: 33

How to use generics with React.FC

How to use generics with React.FC ?

code:

import React from 'react'

export interface IWaterFallProps<T> {
    className?: string;
    style?: React.CSSProperties;
    children?: React.ReactNode;
    dataSource?: T[];
    rowKey?: ((item: T) => string) | string;
    renderItem?: (item: T, index: number) => React.ReactNode;
    header?: React.ReactNode;
    footer?: React.ReactNode;
}


// this T error
const WaterFall: React.FC<IWaterFallProps<T>> = props => {
    return (
        <div 
            className={Styles['waterfall-container']}
            style={props.style}
        >
            {props.header}
            {props.children}
            {props.footer}
        </div>
    )
}

WaterFall.defaultProps = {
    dataSource: [],
}
export default React.memo(WaterFall)

'const WaterFall: React.FC<IWaterFallProps<T>> = props => {}'

this T is not right, and how to do that it work?

link: playground

Upvotes: 3

Views: 788

Answers (1)

zhuber
zhuber

Reputation: 5524

Just use normal function declaration

function WaterFall<T>(props: React.PropsWithChildren<IWaterFallProps<T>>) {
    // your code
}

I've seen tons of hacks and ways to implement this behaviour with "complicated" types and wrappers, but I don't see a need for that when you can use normal function declaration as shown above.

Upvotes: 5

Related Questions