Skip to content

Commit

Permalink
fix key in child elements
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielHara committed Jan 30, 2024
1 parent f9ce544 commit 0c20a08
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 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="yes" /></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
15 changes: 13 additions & 2 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(/^\./)) {
if (typeof key === 'string') {
let updatedKey = key;
// React automatically add ".$" to the original key when the element is a child which has a key prop
if (key.indexOf('.$') === 0) {
updatedKey = key.slice('.$'.length);
}
// React automatically add key=".X" when there are some children
props.key = key;
else if (key.indexOf('.') === 0) {
updatedKey = null;
}

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

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

0 comments on commit 0c20a08

Please sign in to comment.