Skip to content

fix: keep key in child elements, fixes #301 #841

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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