0
# React Element to JSX String
1
2
React Element to JSX String converts React elements into their corresponding JSX string representations. It provides comprehensive support for complex React structures including deep nesting, various prop types, deterministic prop ordering, and configurable formatting options.
3
4
## Package Information
5
6
- **Package Name**: react-element-to-jsx-string
7
- **Package Type**: npm
8
- **Language**: JavaScript (with TypeScript definitions)
9
- **Installation**: `npm install react-element-to-jsx-string` or `yarn add react-element-to-jsx-string`
10
11
## Core Imports
12
13
```typescript
14
import reactElementToJSXString from "react-element-to-jsx-string";
15
```
16
17
With named exports:
18
19
```typescript
20
import reactElementToJSXString, { inlineFunction, preserveFunctionLineBreak } from "react-element-to-jsx-string";
21
```
22
23
CommonJS:
24
25
```javascript
26
const reactElementToJSXString = require("react-element-to-jsx-string");
27
const { inlineFunction, preserveFunctionLineBreak } = require("react-element-to-jsx-string");
28
```
29
30
## Basic Usage
31
32
```typescript
33
import React from 'react';
34
import reactElementToJSXString from 'react-element-to-jsx-string';
35
36
const element = <div a="1" b="2">Hello, world!</div>;
37
console.log(reactElementToJSXString(element));
38
// Output:
39
// <div
40
// a="1"
41
// b="2"
42
// >
43
// Hello, world!
44
// </div>
45
46
// With options
47
const options = {
48
showDefaultProps: false,
49
tabStop: 4,
50
useBooleanShorthandSyntax: false
51
};
52
console.log(reactElementToJSXString(element, options));
53
```
54
55
## Capabilities
56
57
### Main Conversion Function
58
59
Converts a React element into its corresponding JSX string representation.
60
61
```typescript { .api }
62
/**
63
* Convert a React element to JSX string
64
* @param element - The React element to convert
65
* @param options - Configuration options for JSX string generation
66
* @returns JSX string representation
67
*/
68
function reactElementToJSXString(
69
element: ReactNode,
70
options?: ReactElementToJSXStringOptions
71
): string;
72
73
interface ReactElementToJSXStringOptions {
74
/** Custom function to determine element display names */
75
displayName?: (element: ReactNode) => string;
76
/** Filter props by name array or custom function */
77
filterProps?: string[] | FilterPropsFunction;
78
/** Show default props in output (default: true) */
79
showDefaultProps?: boolean;
80
/** Show function bodies instead of placeholder (default: false) */
81
showFunctions?: boolean;
82
/** Custom function value formatter */
83
functionValue?: (fn: any) => any;
84
/** Number of spaces for indentation (default: 2) */
85
tabStop?: number;
86
/** Use boolean shorthand syntax like `enabled` instead of `enabled={true}` (default: true) */
87
useBooleanShorthandSyntax?: boolean;
88
/** Maximum characters per line for inline attributes */
89
maxInlineAttributesLineLength?: number;
90
/** Sort props alphabetically (default: true) */
91
sortProps?: boolean;
92
/** Use fragment short syntax `<>...</>` when possible (default: true) */
93
useFragmentShortSyntax?: boolean;
94
}
95
96
type FilterPropsFunction = (value: any, key: string) => boolean;
97
```
98
99
**Usage Examples:**
100
101
```typescript
102
import React from 'react';
103
import reactElementToJSXString from 'react-element-to-jsx-string';
104
105
// Basic conversion
106
const basicElement = <button onClick={() => console.log('clicked')}>Click me</button>;
107
console.log(reactElementToJSXString(basicElement));
108
109
// With nested elements
110
const nestedElement = (
111
<div className="container">
112
<h1>Title</h1>
113
<p>Some text with <strong>bold</strong> content</p>
114
</div>
115
);
116
console.log(reactElementToJSXString(nestedElement));
117
118
// With custom options
119
const customElement = <input type="text" required disabled={false} />;
120
const customOptions = {
121
useBooleanShorthandSyntax: false,
122
showDefaultProps: false,
123
tabStop: 4
124
};
125
console.log(reactElementToJSXString(customElement, customOptions));
126
127
// Filtering props
128
const elementWithManyProps = <div id="test" className="example" data-testid="my-div" key="unique">Content</div>;
129
const filteredOptions = {
130
filterProps: ['data-testid', 'key'] // Remove these props from output
131
};
132
console.log(reactElementToJSXString(elementWithManyProps, filteredOptions));
133
134
// Custom function filtering
135
const functionFilterOptions = {
136
filterProps: (value, key) => !key.startsWith('data-') // Remove all data- attributes
137
};
138
console.log(reactElementToJSXString(elementWithManyProps, functionFilterOptions));
139
```
140
141
### Function Formatting Utilities
142
143
Utilities for formatting function values in JSX output.
144
145
```typescript { .api }
146
/**
147
* Format function as inline string (removes line breaks)
148
* @param fn - Function to format
149
* @returns Inline string representation
150
*/
151
function inlineFunction(fn: any): string;
152
153
/**
154
* Format function preserving original line breaks
155
* @param fn - Function to format
156
* @returns String representation with line breaks preserved
157
*/
158
function preserveFunctionLineBreak(fn: any): string;
159
```
160
161
**Usage Examples:**
162
163
```typescript
164
import reactElementToJSXString, { inlineFunction, preserveFunctionLineBreak } from 'react-element-to-jsx-string';
165
166
// Using custom function formatters
167
const multilineFunction = function handleClick(event) {
168
event.preventDefault();
169
console.log('Button clicked');
170
};
171
172
const element = <button onClick={multilineFunction}>Click me</button>;
173
174
// Default behavior (inline function placeholder)
175
console.log(reactElementToJSXString(element));
176
// Output: <button onClick={function noRefCheck() {}}>Click me</button>
177
178
// Show actual function bodies inline
179
console.log(reactElementToJSXString(element, {
180
showFunctions: true,
181
functionValue: inlineFunction
182
}));
183
// Output: <button onClick={function handleClick(event) { event.preventDefault(); console.log('Button clicked'); }}>Click me</button>
184
185
// Preserve function line breaks
186
console.log(reactElementToJSXString(element, {
187
showFunctions: true,
188
functionValue: preserveFunctionLineBreak
189
}));
190
// Output: function with original formatting preserved
191
```
192
193
## Advanced Configuration
194
195
### Display Name Customization
196
197
```typescript
198
const CustomComponent = () => <div>Custom</div>;
199
const element = <CustomComponent />;
200
201
const options = {
202
displayName: (element) => {
203
if (element.type.name === 'CustomComponent') {
204
return 'MyCustomComponent';
205
}
206
return element.type.displayName || element.type.name || 'Unknown';
207
}
208
};
209
210
console.log(reactElementToJSXString(element, options));
211
// Output: <MyCustomComponent />
212
```
213
214
### Inline Attributes Control
215
216
```typescript
217
const element = <input type="text" placeholder="Enter text" className="form-control" required />;
218
219
// Inline short attributes
220
const inlineOptions = {
221
maxInlineAttributesLineLength: 60
222
};
223
console.log(reactElementToJSXString(element, inlineOptions));
224
// Output: <input type="text" placeholder="Enter text" className="form-control" required />
225
226
// Force multiline attributes
227
const multilineOptions = {
228
maxInlineAttributesLineLength: 20
229
};
230
console.log(reactElementToJSXString(element, multilineOptions));
231
// Output:
232
// <input
233
// type="text"
234
// placeholder="Enter text"
235
// className="form-control"
236
// required
237
// />
238
```
239
240
### React Fragments
241
242
```typescript
243
import React, { Fragment } from 'react';
244
245
// Fragment with short syntax
246
const shortFragment = (
247
<>
248
<div>First</div>
249
<div>Second</div>
250
</>
251
);
252
253
console.log(reactElementToJSXString(shortFragment));
254
// Output:
255
// <>
256
// <div>First</div>
257
// <div>Second</div>
258
// </>
259
260
// Force explicit Fragment syntax
261
const explicitOptions = {
262
useFragmentShortSyntax: false
263
};
264
console.log(reactElementToJSXString(shortFragment, explicitOptions));
265
// Output:
266
// <React.Fragment>
267
// <div>First</div>
268
// <div>Second</div>
269
// </React.Fragment>
270
271
// Keyed fragments always use explicit syntax
272
const keyedFragment = (
273
<Fragment key="my-fragment">
274
<div>Content</div>
275
</Fragment>
276
);
277
console.log(reactElementToJSXString(keyedFragment));
278
// Output:
279
// <React.Fragment key="my-fragment">
280
// <div>Content</div>
281
// </React.Fragment>
282
```
283
284
## Types
285
286
```typescript { .api }
287
interface ReactElementToJSXStringOptions {
288
displayName?: (element: ReactNode) => string;
289
filterProps?: string[] | FilterPropsFunction;
290
showDefaultProps?: boolean;
291
showFunctions?: boolean;
292
functionValue?: (fn: any) => any;
293
tabStop?: number;
294
useBooleanShorthandSyntax?: boolean;
295
maxInlineAttributesLineLength?: number;
296
sortProps?: boolean;
297
useFragmentShortSyntax?: boolean;
298
}
299
300
type FilterPropsFunction = (value: any, key: string) => boolean;
301
```
302
303
## Error Handling
304
305
The library throws errors in the following cases:
306
307
```typescript
308
// Throws: "react-element-to-jsx-string: Expected a ReactElement"
309
reactElementToJSXString(null);
310
reactElementToJSXString(undefined);
311
312
// Throws: "react-element-to-jsx-string: Expected a React.Element, got `object`"
313
reactElementToJSXString({});
314
reactElementToJSXString([]);
315
```
316
317
Always ensure you pass a valid React element to avoid runtime errors.