Created
October 19, 2020 16:14
-
-
Save tomsseisums/947fc6351a388c546d68243f0861a4c6 to your computer and use it in GitHub Desktop.
React/TypeScript Component Mapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createElement } from 'react' | |
interface MapType { | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
[key: string]: (...args: any) => any | |
} | |
export default function componentMapperFactory<T extends MapType>( | |
contentTypeMap: T | |
) { | |
function factory<K extends keyof T>({ | |
type, | |
props, | |
}: { | |
type: K | |
props: Parameters<T[K]>[0] | |
}) { | |
const Component = contentTypeMap[type] | |
if (!Component) { | |
return null | |
} | |
return createElement(Component, props) | |
} | |
return factory | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import componentMapperFactory from '<path to>/componentMapperFactory' | |
import PictureDetail from './PictureDetail' | |
import CopyDetail from './CopyDetail' | |
import VideoDetail from './VideoDetail' | |
import SomeOtherDetailType from './SomeOtherDetailType' | |
export default componentMapperFactory({ | |
picture: PictureDetail, | |
copy: CopyDetail, | |
video: VideoDetail, | |
'some-other-detail-type': SomeOtherDetailType | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment