@@ -69,44 +69,58 @@ export interface TemplateComponentProps extends HTMLAttributes<HTMLElement> {
6969const TemplateComponentInternal : FunctionComponent < TemplateComponentProps > =
7070 forwardRef < ComponentType , TemplateComponentProps > (
7171 ( { template, sanitize, sanitizeOptions, data, type, ...args } , ref ) => {
72- try {
73- const sanitizer = dompurify . sanitize ;
74- const compiled = useMemo (
75- ( ) =>
76- typeof template === "string"
77- ? Mustache . render ( template , data )
78- : null ,
79- [ template , data ] ,
80- ) ;
81- const shouldSanitize = typeof sanitize === "boolean" ? sanitize : true ;
82- const innerType = type || "div" ;
72+ const sanitizer = dompurify . sanitize ;
73+ const shouldSanitize = typeof sanitize === "boolean" ? sanitize : true ;
74+ const innerType = type || "div" ;
8375
76+ const compiled = useMemo ( ( ) => {
77+ if ( typeof template === "string" ) {
78+ try {
79+ return Mustache . render ( template , data ) ;
80+ } catch ( error ) {
81+ // eslint-disable-next-line no-console
82+ console . error ( error ) ;
83+ return null ;
84+ }
85+ }
86+ return null ;
87+ } , [ template , data ] ) ;
88+
89+ const html = useMemo ( ( ) => {
8490 if ( compiled === null ) {
8591 return null ;
8692 }
93+ try {
94+ return (
95+ shouldSanitize
96+ ? typeof sanitizeOptions !== "undefined"
97+ ? sanitizer ( compiled , sanitizeOptions )
98+ : sanitizer ( compiled )
99+ : compiled
100+ ) as string ;
101+ } catch ( error ) {
102+ // eslint-disable-next-line no-console
103+ console . error ( error ) ;
104+ return null ;
105+ }
106+ } , [ compiled ] ) ;
87107
88- const html = (
89- shouldSanitize
90- ? typeof sanitizeOptions !== "undefined"
91- ? sanitizer ( compiled , sanitizeOptions )
92- : sanitizer ( compiled )
93- : compiled
94- ) as string ;
95-
96- const htmlOpts = useMemo (
97- ( ) => ( {
98- ...args ,
99- dangerouslySetInnerHTML : { __html : html } ,
100- } ) ,
101- [ html ] ,
102- ) ;
108+ const htmlOpts = useMemo (
109+ ( ) =>
110+ html
111+ ? {
112+ ...args ,
113+ dangerouslySetInnerHTML : { __html : html } ,
114+ }
115+ : args ,
116+ [ html ] ,
117+ ) ;
103118
104- return createElement ( innerType , { ...htmlOpts , ref } , null ) ;
105- } catch ( error ) {
106- // eslint-disable-next-line no-console
107- console . error ( error ) ;
119+ if ( ! html ) {
108120 return null ;
109121 }
122+
123+ return createElement ( innerType , { ...htmlOpts , ref } , null ) ;
110124 } ,
111125 ) ;
112126
0 commit comments