@@ -2,38 +2,36 @@ import React from 'react'
22import * as Emoji from './index'
33import './default-svg.css'
44
5- function reactReplaceEmojis ( reactChild , options ) {
6- let newReactChild ;
7- if ( Array . isArray ( reactChild . props . children ) ) {
8- let newChildren = [ ] ;
9- for ( let i in reactChild . props . children ) {
10- if ( ! reactChild . props . children . hasOwnProperty ( i ) ) continue
11- const child = reactChild . props . children [ Number ( i ) ] ;
12- if ( React . isValidElement ( child ) ) {
13- newChildren [ i ] = reactReplaceEmojis ( child , options )
14- } else {
15- newChildren [ i ] = React . cloneElement (
16- reactChild ,
17- { } ,
18- replaceEmojis ( child , options )
19- )
20- }
5+ export default function reactReplaceEmojis ( reactElement , options ) {
6+ // shortcut -> no children means nothing to replace
7+ if ( ! reactElement . props . children ) return reactElement
8+ let newReactElement ,
9+ hasMultipleChildren = Array . isArray ( reactElement . props . children ) ,
10+ newChildren = [ ]
11+
12+ // if element has multiple children call the recursive function once for each
13+ if ( hasMultipleChildren ) {
14+ for ( let i in reactElement . props . children ) {
15+ if ( ! reactElement . props . children . hasOwnProperty ( i ) ) continue
16+ const child = reactElement . props . children [ Number ( i ) ] ;
17+ newChildren [ i ] = _applyCorrectReplace ( child , options )
2118 }
22- newReactChild = React . cloneElement (
23- reactChild ,
24- { } ,
25- newChildren
26- ) ;
27- } else {
28- newReactChild = React . cloneElement (
29- reactChild ,
30- { } ,
31- replaceEmojis ( reactChild . props . children , options )
32- )
33- }
34- return newReactChild ;
19+ } else // if element has only one child call the recursive function directly
20+ newChildren = _applyCorrectReplace ( reactElement . props . children , options )
21+
22+ newReactElement = React . cloneElement (
23+ reactElement ,
24+ { } ,
25+ newChildren
26+ ) ;
27+ return newReactElement ;
3528}
3629
30+ const _applyCorrectReplace = ( child , options ) =>
31+ React . isValidElement ( child )
32+ ? reactReplaceEmojis ( child , options )
33+ : replaceEmojis ( child , options )
34+
3735export function replaceEmojis ( string , options ) {
3836 if ( ! string ) return ;
3937 let array = [ string ]
0 commit comments