diff --git a/index.tsx b/index.tsx index 0942457..90ac45b 100644 --- a/index.tsx +++ b/index.tsx @@ -1,39 +1,33 @@ /* eslint-disable react/jsx-no-useless-fragment */ -import * as React from 'react'; +import React, { memo, useMemo } from "react"; -type WhenProps = { - children: React.ReactNode, - isTrue?: boolean, - limit?: number, -}; +type WhenProps = React.PropsWithChildren<{ + condition?: boolean; + limit?: number; +}>; -const RenderWhen = ({ limit, isTrue, children }:WhenProps) => { - const list:React.ReactNode[] = []; +const Wrapper: React.FC = memo( + ({ limit = 1, condition = true, children }) => { + const list = useMemo(() => { + return React.Children.map(children, (child) => { + const { condition: childCondition } = child?.props || {}; - if (isTrue !== true) { - return null; - } - - React.Children.map(children, (child:any) => { - const { isTrue: isChildTrue } = child?.props || {}; - - if (isChildTrue === true && list.length < limit) { - list.push(child); + if (childCondition && list.length < limit) { + return child; } - }); + }); + }, [children, limit]); - return ( - <> - {list} - - ); -}; + if (!condition) { + return null; + } -RenderWhen.defaultProps = { - limit: 1, - isTrue: true, -}; + return <>{list}; + } +); -RenderWhen.If = ({ children, isTrue }) => children; +const If: React.FC = memo(({ children }) => { + return children; +}); -export default RenderWhen; +export default { Wrapper, If };