|
1 | 1 | import * as React from 'react'; |
2 | 2 | import { tokenize, Options } from 'linkifyjs'; |
3 | 3 |
|
4 | | -// Given a string, converts to an array of valid React components |
5 | | -// (which may include strings) |
| 4 | +/** |
| 5 | + * Given a string, converts to an array of valid React components |
| 6 | + * (which may include strings) |
| 7 | + * @param {string} str |
| 8 | + * @param {any} opts |
| 9 | + * @returns {React.ReactNodeArray} |
| 10 | + */ |
6 | 11 | function stringToElements(str, opts) { |
7 | 12 |
|
8 | 13 | const tokens = tokenize(str); |
@@ -52,6 +57,14 @@ function stringToElements(str, opts) { |
52 | 57 | } |
53 | 58 |
|
54 | 59 | // Recursively linkify the contents of the given React Element instance |
| 60 | +/** |
| 61 | + * @template P |
| 62 | + * @template {string | React.JSXElementConstructor<P>} T |
| 63 | + * @param {React.ReactElement<P, T>} element |
| 64 | + * @param {Object} opts |
| 65 | + * @param {number} elementId |
| 66 | + * @returns {React.ReactElement<P, T>} |
| 67 | + */ |
55 | 68 | function linkifyReactElement(element, opts, elementId = 0) { |
56 | 69 | if (React.Children.count(element.props.children) === 0) { |
57 | 70 | // No need to clone if the element had no children |
@@ -90,22 +103,24 @@ function linkifyReactElement(element, opts, elementId = 0) { |
90 | 103 | } |
91 | 104 |
|
92 | 105 | /** |
93 | | - * @param {Object} props |
94 | | - * @param {Object} [props.options] Linkify options |
95 | | - * @param {string | React.Element} [props.tagName] element in which to wrap all Linkified content (default React.Fragment) |
| 106 | + * @template P |
| 107 | + * @template {string | React.JSXElementConstructor<P>} T |
| 108 | + * @param {P & { tagName?: T, options?: any, children?: React.ReactNode}} props |
| 109 | + * @returns {React.ReactElement<P, T>} |
96 | 110 | */ |
97 | 111 | const Linkify = (props) => { |
98 | 112 | // Copy over all non-linkify-specific props |
99 | 113 | const newProps = { key: 'linkified-element-wrapper' }; |
100 | 114 | for (const prop in props) { |
101 | | - if (prop !== 'options' && prop !== 'tagName') { |
| 115 | + if (prop !== 'options' && prop !== 'tagName' && prop !== 'children') { |
102 | 116 | newProps[prop] = props[prop]; |
103 | 117 | } |
104 | 118 | } |
105 | 119 |
|
106 | 120 | const opts = new Options(props.options); |
107 | 121 | const tagName = props.tagName || React.Fragment || 'span'; |
108 | | - const element = React.createElement(tagName, newProps); |
| 122 | + const children = props.children; |
| 123 | + const element = React.createElement(tagName, newProps, children); |
109 | 124 |
|
110 | 125 | return linkifyReactElement(element, opts, 0); |
111 | 126 | }; |
|
0 commit comments