Skip to content

Commit

Permalink
fix: handle empty objects
Browse files Browse the repository at this point in the history
  • Loading branch information
vvo committed Oct 16, 2015
1 parent 4138ecc commit fe052bd
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 14 deletions.
18 changes: 15 additions & 3 deletions index-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -182,9 +182,21 @@ describe(`reactElementToJSXString(ReactElement)`, () => {
).toEqual(`<div a={{b: function noRefCheck() {}}} />`);
});

it(`reactElementToJSXString(<div a={{b: {c: {d: <div />}}}} />`, () => {
it(`reactElementToJSXString(<div a={{b: {c: {d: <div />, e: null}}}} />`, () => {
expect(
reactElementToJSXString(<div a={{b: {c: {d: <div />}}}} />)
).toEqual(`<div a={{b: {c: {d: <div />}}}} />`);
reactElementToJSXString(<div a={{b: {c: {d: <div />, e: null}}}} />)
).toEqual(`<div a={{b: {c: {d: <div />, e: null}}}} />`);
});

it(`reactElementToJSXString(<div a={{b: {}}} />`, () => {
expect(
reactElementToJSXString(<div a={{b: {}}} />)
).toEqual(`<div a={{b: {}}} />`);
});

it(`reactElementToJSXString(<div a={{}} />`, () => {
expect(
reactElementToJSXString(<div a={{}} />)
).toEqual(`<div a={{}} />`);
});
});
26 changes: 15 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ function formatProps(props) {
return {
name: propName,
value: formatPropValue(props[propName])
.replace(/'?<__reactElementToJSXString__ReactElement__>/g, '')
.replace(/<\/__reactElementToJSXString__ReactElement__>'?/g, '')
.replace(/'?<__reactElementToJSXString__Wrapper__>/g, '')
.replace(/<\/__reactElementToJSXString__Wrapper__>'?/g, '')
};
});
}
Expand All @@ -110,11 +110,13 @@ function formatValue(value) {
// // <div a={{b: <div />}} />
// we then remove the whole wrapping
// otherwise, the element would be surrounded by quotes: <div a={{b: '<div />'}} />
return '<__reactElementToJSXString__ReactElement__>' +
return '<__reactElementToJSXString__Wrapper__>' +
toJSXString({ReactElement: value, inline: true}) +
'</__reactElementToJSXString__ReactElement__>';
'</__reactElementToJSXString__Wrapper__>';
} else if (isPlainObject(value)) {
return stringifyObject(value);
return '<__reactElementToJSXString__Wrapper__>' +
stringifyObject(value) +
'</__reactElementToJSXString__Wrapper__>';
}

return value;
Expand All @@ -127,13 +129,15 @@ function recurse({lvl, inline}) {
}

function stringifyObject(obj) {
obj = traverse(obj).map(function(value) {
if (isElement(value) || this.isLeaf) {
this.update(formatValue(value));
}
});
if (Object.keys(obj).length > 0) {
obj = traverse(obj).map(function(value) {
if (isElement(value) || this.isLeaf) {
this.update(formatValue(value));
}
});

obj = sortobject(obj);
obj = sortobject(obj);
}

return collapse(stringify(obj))
.replace(/{ /g, '{')
Expand Down

0 comments on commit fe052bd

Please sign in to comment.