Saturday, 19 November 2022

React TypeScript custom wrapper around semantic-ui components

I'm using typescript (Beginner) and trying to create a Wrapper function around some semantic-ui-react components. This Wrapper will set my custom styles and return semantic-ui components memoized with childrens inside. At the moment I got this error on my Element component :

Type '{ children: ReactNode; className: string; }' is not assignable to type 'T'.   'T' could be instantiated with an arbitrary type which could be unrelated to '{ children: ReactNode; className: string; }'

Here is my code :

//Wrapper.tsx
type WrapperContent = PropsWithChildren<{
    className?: string
    [x: string]: any // All others props
}>

function Wrapper<T>(
    Element: ComponentType<T>,
    styles: string,
): NamedExoticComponent<ComponentType<T>> {
    const memoFct = (({ children, className, ...props } : WrapperContent) => (
        <Element {...props} className={classNames(styles, className)}>
            { children }
        </Element>
    ))

    return memo(memoFct)
}
//Grid.ts
import { Grid as SemanticGrid, GridProps } from 'semantic-ui-react'
import Wrapper from 'ui/Wrapper'
import styles from './styles.module.scss'

const Grid = Wrapper<GridProps>(SemanticGrid, styles.grid)

After that, i'm using Grid component in my application with children like this :

<Grid stackable columns={2}>
    ...Other components
</Grid>

I saw working with memo and children at the same time can cause some problems on others topics.
Someone already tried to create a Generic Wrapper around some components ?



from React TypeScript custom wrapper around semantic-ui components

No comments:

Post a Comment