Skip to content

Commit

Permalink
fix: keep key in child elements, fixes algolia#301
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielHara committed Jan 30, 2024
1 parent f9ce544 commit bb921d1
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 3 deletions.
20 changes: 20 additions & 0 deletions src/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -725,6 +725,26 @@ describe('reactElementToJSXString(ReactElement)', () => {
);
});

it('reactElementToJSXString(<div aprop="test" key="yes"><div aprop="test" key="abc" /></div>', () => {
expect(
reactElementToJSXString(
<div aprop="test" key="yes">
<div aprop="test" key="abc" />
</div>
)
).toEqual(
`<div
key="yes"
aprop="test"
>
<div
key="abc"
aprop="test"
/>
</div>`
);
});

it('reactElementToJSXString(<div>\\n {null}\\n</div>', () => {
const element = <div>{null}</div>;

Expand Down
17 changes: 14 additions & 3 deletions src/parser/parseReactElement.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,9 +117,20 @@ const parseReactElement = (
}

const key = element.key;
if (typeof key === 'string' && key.search(/^\./)) {
// React automatically add key=".X" when there are some children
props.key = key;
if (typeof key === 'string') {
let originalKey = key;
// React automatically adds ".$" to the original key when the element is a child which has a key prop
if (key.indexOf('.$') === 0) {
originalKey = key.slice('.$'.length);
}
// React automatically adds key=".X" when there are some children
else if (key.indexOf('.') === 0) {
originalKey = null;
}

if (originalKey) {
props.key = originalKey;
}
}

const defaultProps = filterProps(element.type.defaultProps || {}, noChildren);
Expand Down

0 comments on commit bb921d1

Please sign in to comment.