Skip to content

Commit

Permalink
feat: handle key=""
Browse files Browse the repository at this point in the history
  • Loading branch information
vvo committed Oct 24, 2015
1 parent 5b18191 commit da85281
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Features:
- props: supports string, number, function (inlined as `prop={function noRefCheck() {}}`), object, ReactElement (inlined), regex..
- 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

<!-- START doctoc generated TOC please keep comment here to allow auto update -->
Expand Down
10 changes: 10 additions & 0 deletions index-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -328,4 +328,14 @@ describe(`reactElementToJSXString(ReactElement)`, () => {
/>
</div>`);
});

it(`reactElementToJSXString(<div aprop="test" key="yes" />`, () => {
expect(
reactElementToJSXString(<div aprop="test" key="yes" />)
).toEqual(
`<div
key="yes"
aprop="test"
/>`);
});
});
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,12 @@ function toJSXString({ReactElement = null, lvl = 0, inline = false}) {
attributes.push(getJSXAttribute('ref', ReactElement.ref));
}

if (ReactElement.key !== null &&
// React automatically add key=".X" when there are some children
!/^\./.test(ReactElement.key)) {
attributes.push(getJSXAttribute('key', ReactElement.key));
}

attributes = attributes.concat(props);

attributes.forEach(attribute => {
Expand Down

0 comments on commit da85281

Please sign in to comment.