Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

react-element-to-jsx-string

algolia15.1mMIT17.0.0TypeScript support: included

Turn a ReactElement into the corresponding JSX string.

readme

react-element-to-jsx-string

Version Build Status License Downloads

Turn a ReactElement into the corresponding JSX string.

Useful for unit testing and any other need you may think of.

Features:

  • supports nesting and deep nesting like <div a={{b: {c: {d: <div />}}}} />
  • props: supports string, number, function (inlined as prop={function noRefCheck() {}}), object, ReactElement (inlined), regex, booleans (with or without shorthand syntax), ...
  • order props alphabetically
  • sort object keys in a deterministic order (o={{a: 1, b:2}} === o={{b:2, a:1}})
  • handle ref and key attributes, they are always on top of props
  • React's documentation indent style for JSX

Table of Contents generated with DocToc

Setup

yarn add react-element-to-jsx-string [--dev]

Usage

import React from 'react';
import reactElementToJSXString from 'react-element-to-jsx-string';

console.log(reactElementToJSXString(<div a="1" b="2">Hello, world!</div>));
// <div
//   a="1"
//   b="2"
// >
//   Hello, world!
// </div>

API

reactElementToJSXString(ReactElement[, options])

options.displayName: function(ReactElement)

Provide a different algorithm in charge of finding the right display name (name of the underlying Class) for your element.

Just return the name you want for the provided ReactElement, as a string.

options.filterProps: string[] | (val: any, key: string) => boolean, default []

If an array of strings is passed, filter out any prop who's name is in the array. For example ['key'] will suppress the key="" prop from being added.

If a function is passed, it will be called for each prop with two arguments, the prop value and key, and will filter out any that return false.

options.showDefaultProps: boolean, default true

If true, default props shown.

If false, default props are omitted unless they differ from from the default value.

options.showFunctions: boolean, default false

If true, functions bodies are shown.

If false, functions bodies are replaced with function noRefCheck() {}.

options.functionValue: function, default (fn) => fn

Allows you to override the default formatting of function values.

functionValue receives the original function reference as input and should send any value as output.

options.tabStop: number, default 2

Provide a different number of columns for indentation.

options.useBooleanShorthandSyntax: boolean, default true

If true, Boolean prop values will be omitted for shorthand syntax.

If false, Boolean prop values will be explicitly output like prop={true} and prop={false}

options.maxInlineAttributesLineLength: number, default undefined

Allows to render multiple attributes on the same line and control the behaviour.

You can provide the max number of characters to render inline with the tag name. If the number of characters on the line (including spacing and the tag name) exceeds this number, then all attributes will be rendered on a separate line. The default value of this option is undefined. If this option is undefined then if there is more than one attribute on an element, they will render on their own line. Note: Objects passed as attribute values are always rendered on multiple lines

options.sortProps: boolean, default true

Either to sort or not props. If you use this lib to make some isomorphic rendering you should set it to false, otherwise this would lead to react invalid checksums as the prop order is part of react isomorphic checksum algorithm.

options.useFragmentShortSyntax: boolean, default true

If true, fragment will be represented with the JSX short syntax <>...</> (when possible).

If false, fragment will always be represented with the JSX explicit syntax <React.Fragment>...</React.Fragment>.

According to the specs:

  • A keyed fragment will always use the explicit syntax: <React.Fragment key={...}>...</React.Fragment>
  • An empty fragment will always use the explicit syntax: <React.Fragment />

    Note: to use fragment you must use React >= 16.2

Environment requirements

The environment you use to use react-element-to-jsx-string should have ES2015 support.

Use the Babel polyfill or any other method that will make you environment behave like an ES2015 environment.

Test

yarn test
yarn test:watch

Build

yarn build
yarn build:watch

Release

Decide if this is a patch, minor or major release, look at http://semver.org/

npm run release [major|minor|patch|x.x.x]

Thanks

alexlande/react-to-jsx was a good source of inspiration.

We built our own module because we had some needs like ordering props in alphabetical order.

changelog

17.0.0 (2025-01-18)

Bug Fixes

  • deps: update dependency @base2/pretty-print-object to v1.0.2 (3431228)

BREAKING CHANGES

  • To simplify the library maintenance, this major version only support React 19.

15.0.0 (2022-05-09)

Bug Fixes

14.3.4 (2021-10-19)

Bug Fixes

  • stringifying elements with props containing circular references (#660) (f203060)

14.3.3 (2021-10-19)

Bug Fixes

Features

14.3.2 (2020-10-28)

Bug Fixes

  • deps: update dependency is-plain-object to v3.0.1 (4974512)
  • Handle multiple words before trailing space (#572) (e0c082e)

14.3.1 (2020-01-21)

Bug Fixes

14.3.0 (2020-01-17)

Features

14.2.0 (2019-12-29)

Bug Fixes

  • deps: pin dependency @base2/pretty-print-object to 1.0.0 (07f19f9)
  • formatting: fix the anonymous functional component detection after babel upgrade (7a1b93e)

Features

  • typescript: Add TypeScript declaration file. (#475) (f9ea4e5)

14.1.0 (2019-09-15)

Bug Fixes

  • deps: Remove dependency stringify-object (6dc6d8d)
  • deps: Replace dependency stringify-object with pretty-print-object (940a413)

14.0.3 (2019-07-19)

Bug Fixes

  • deps: update dependency is-plain-object to v3 (#361) (b58cbbd)
  • Rework the propNameSorter to be less dependents of node sort internals (a9ee312)
  • deps: update dependency stringify-object to v3.3.0 (bfe9a9f)
  • formatting: Make the props "key" and "ref" order predictibale (#340) (3853463)

chore

  • deps: update jest monorepo to v23 (major) (#305) (aef55a2)

Features

BREAKING CHANGES

  • deps: If you use the showFunctions: true option, the function are now always inlined in the output by default. Before it was not always the case (depending one the engine, platform or babel versions)

You could get back to the previous behavior by using the preserveFunctionLineBreak function export as a value of the option functionValue.

  • test(smoke): Adapt the CommonJS bundle import

14.0.2 (2018-10-10)

Bug Fixes

  • formatting: Fix JSX element in prop object recursive loop (#309) (fd4f53b)
  • functionValue: handle nested datastructures (94d1aeb)

14.0.1 (2018-06-20)

Bug Fixes

14.0.0 (2018-05-25)

Features

  • browser: build a dedicated version for the browser (#242) (574d850)

BREAKING CHANGES

  • browser: This PR change of the internal directory structure of the exported code. The previous code has move from the dist/ into the dist/esm directory (but remender that we do not avice you to do use internals code 🤓)

  • fix(bunble): do not bundle peer dependencies

  • qa(ci): Avoid duplicate runs of checks on CI

  • qa(dependencies): Upgrade to latest rollup versions

  • qa(test): Allow to run the smoke tests aggaint all builded versions

13.2.0 (2018-03-14)

Bug Fixes

  • deps: update dependency stringify-object to v3.2.2 (b1a4c5e)

13.1.0 (2017-11-15)

Bug Fixes

  • formatting: Date/RegExp values output by formatComplexDataStructure (#250) (0387b72)
  • react: Fix warning about access to PropTypes using React 15.5+ (fixes #213) (2dcfd10)
  • test: Fix usage of yarn instead of npm in test script (0db5aa4)

13.0.0 (2017-10-09)

Bug Fixes

  • deps: update dependency stringify-object to v3.2.1 (539ea56)
  • formatting: symbol description are now quoted (2747f1b), closes #134
  • formatting: trailing space (2a07d5e), closes #135

BREAKING CHANGES

  • formatting: Trailing are now preserved. In some rare case, react-element-to-jsx-string failed to respect the JSX specs for the trailing space. Event is the space were in the final output. There were silentrly ignored by JSX parser. This commit fix this bug by protecting the trailing space in the output.

If we take the JSX:

<div>
  foo <strong>bar</strong> baz
</div>

Before it was converted to (the trailing space are replace by * for the readability):

<div>
  foo*
  <strong>
    bar
  </strong>
  *baz
</div>

Now there are preserved:

<div>
  foo{' '}
  <strong>
    bar
  </strong>
  {' '}baz
</div>
  • formatting: Symbol description are now correctly quoted. This change the output if you use Symbol in your code

12.0.0 (2017-08-03)

Bug Fixes

  • flow: export flow definitions in the released bundle and fix the npm ignore too restrictive (#115) (c4f91b9)
  • formatting: Children with multiline string are now correctly indented (d18809e)
  • formatting: Fix JSX delimiters escaping in string (6e0eea3)
  • release: revert change made by error in commit 86697517 (903fd5c)
  • travis: manually install yarn on Travis CI (b8a4c1a)

BREAKING CHANGES

  • formatting: Improve string escaping of string that contains JSX delimiters ({,},<,>)

Before:

console.log(reactElementToJsxString(<div>{`Mustache :{`}</div>);

// <div>Mustache :&lbrace;</div>

Now:

console.log(reactElementToJsxString(<div>{`Mustache :{`}</div>);

// <div>{`Mustache :{`}</div>

11.0.1 (2017-07-21)

Bug Fixes

  • formatting: fix an edge case where number and string childrens are not correctly merged (47572e0)

11.0.0 (2017-07-20)

Bug Fixes

  • release: Missing mversion package in dev dependencies (0f82ee7)
  • escaping: Complete lib refactor to handle more escaping cases (9f3c671)

BREAKING CHANGES

  • Fix escaping issue with quotes (in props value or in children of type string)
  • Handle props value of Date type: <div foo={new Date("2017-01-01T11:00:00.000Z")} />
  • Escape brace chars ({}) in a children string: <script type="application/json+ld">&lbrace; hello: 'world' &rbrace;</script>

10.1.0 (2017-06-13)

Features

  • sortProps: add option to remove sorting of props (66e8307)

10.0.1 (2017-06-12)

10.0.0 (2017-06-07)

9.0.0 (2017-06-07)

Bug Fixes

8.0.0 (2017-05-24)

7.0.0 (2017-05-14)

6.4.0 (2017-04-24)

Features

  • functionValue: format functions output the way you want (460e0cc)
  • React: support 15.5+ (1a99024)

6.3.0 (2017-03-06)

6.2.0 (2017-02-27)

Features

  • inline attributes: Allow formatting attribute on the same line (da72176)

6.0.0 (2017-01-03)

Chores

  • build: switch to stringify-object@3 (e9a5c7f)

BREAKING CHANGES

  • build: You need an ES2015 env to use react-element-to-jsx-string now

You can use the Babel polyfill to do so.

5.0.7 (2017-01-03)

Bug Fixes

5.0.6 (2017-01-02)

5.0.5 (2017-01-02)

5.0.4 (2016-12-08)

5.0.3 (2016-12-08)

5.0.2 (2016-11-17)

5.0.1 (2016-11-16)

Bug Fixes

  • deps: remove direct dep on react-addons-test-utils (06d2588), closes #56

5.0.0 (2016-10-24)

Features

  • pretty: prettify objects, arrays, nested (864b9db)

BREAKING CHANGES

  • pretty: objects and arrays are now prettified by default following #50 If this is a concern to you, open a PR that adds an option to inline parts or the whole output like before

4.2.0 (2016-09-21)

4.1.0 (2016-08-30)

4.0.0 (2016-08-04)

3.2.0 (2016-07-15)

3.1.2 (2016-07-12)

3.1.1 (2016-07-12)

3.1.0 (2016-06-28)

3.0.0 (2016-05-25)

2.6.1 (2016-04-15)

Bug Fixes

2.6.0 (2016-04-15)

Features

  • React: React v15 compat (37ee7b5)

2.4.0 (2016-02-02)

2.3.0 (2016-02-02)

Features

2.2.0 (2016-01-14)

2.1.5 (2016-01-05)

2.1.4 (2015-12-10)

Bug Fixes

  • stateless comps: add No Display Name as default component name (dc0f65c), closes #11

2.1.3 (2015-11-30)

Bug Fixes

  • handle
    {123}
    (609ac78), closes #8
  • lodash: just use plain lodash and import (062b3fe)
  • whitespace: handle {true} {false} (eaca1a2), closes #6 #7
  • whitespace: stop rendering it differently in SOME cases (128aa95)

2.1.0 (2015-10-25)

Features

2.0.5 (2015-10-21)

Bug Fixes

  • merge plain strings props replacements (7c2bf27)

2.0.4 (2015-10-16)

Bug Fixes

  • tagName: fixed an edge-case with decorated component name (9169ac7)

2.0.3 (2015-10-16)

Bug Fixes

  • handle arrays the right way (597a910)

2.0.2 (2015-10-16)

Bug Fixes

  • children: ensure the array of children is well handled (36b462a)

2.0.1 (2015-10-16)

Bug Fixes

2.0.0 (2015-10-16)

Features

  • deep: handle deeply set functions (ad21917)
  • deep: handle deeply set React elements (a06f329)

BREAKING CHANGES

  • deep: functions are now stringified to function noRefCheck() {} instead of function () {code;}. For various reasons AND to be specific about the fact that we do not represent the function in a realistic way.

1.1.2 (2015-10-16)

Bug Fixes

  • handle null and undefined prop values (9a57a10), closes #1

1.1.1 (2015-10-15)

1.1.0 (2015-10-15)

Bug Fixes

  • whitespace: remove unwanted whitespace in output (3e2e7b8)

Features

  • sort object keys in a deterministic way (c1ce8a6)