From 5b18191e76ef8f3f9652a8b753b7d856410be7a2 Mon Sep 17 00:00:00 2001 From: vvo Date: Sat, 24 Oct 2015 16:47:15 +0200 Subject: [PATCH] feat: handle ref="manual-ref" --- index-test.js | 31 +++++++++++++++++++++++++++++++ index.js | 35 +++++++++++++++++++++++------------ 2 files changed, 54 insertions(+), 12 deletions(-) diff --git a/index-test.js b/index-test.js index bffeca41f..ed0f3bfa7 100644 --- a/index-test.js +++ b/index-test.js @@ -295,6 +295,37 @@ describe(`reactElementToJSXString(ReactElement)`, () => { .toEqual( `
Hello John +
`); + }); + + it(`reactElementToJSXString(
]} />`, () => { + expect( + reactElementToJSXString(
]} />) + ).toEqual(`
]} />`); + }); + + it(`reactElementToJSXString(
`, () => { + expect( + reactElementToJSXString(
) + ).toEqual( +`
`); + }); + + it(`reactElementToJSXString(
`, () => { + expect( + reactElementToJSXString(
) + ).toEqual( +`
+
`); }); }); diff --git a/index.js b/index.js index db963aa40..d7162da38 100644 --- a/index.js +++ b/index.js @@ -31,19 +31,26 @@ function toJSXString({ReactElement = null, lvl = 0, inline = false}) { let out = `<${tagName}`; let props = formatProps(ReactElement.props); + let attributes = []; let children = ReactElement.props.children; - props.forEach(prop => { - if (props.length === 1 || inline) { + if (ReactElement.ref !== null) { + attributes.push(getJSXAttribute('ref', ReactElement.ref)); + } + + attributes = attributes.concat(props); + + attributes.forEach(attribute => { + if (attributes.length === 1 || inline) { out += ` `; } else { out += `\n${spacer(lvl + 1)}`; } - out += `${prop.name}=${prop.value}`; + out += `${attribute.name}=${attribute.value}`; }); - if (props.length > 1 && !inline) { + if (attributes.length > 1 && !inline) { out += `\n${spacer(lvl)}`; } @@ -71,7 +78,7 @@ function toJSXString({ReactElement = null, lvl = 0, inline = false}) { } out += ``; } else { - if (props.length <= 1) { + if (attributes.length <= 1) { out += ` `; } @@ -99,16 +106,20 @@ function formatProps(props) { .filter(noChildren) .sort() .map(propName => { - return { - name: propName, - value: formatPropValue(props[propName]) - .replace(/'?<__reactElementToJSXString__Wrapper__>/g, '') - .replace(/<\/__reactElementToJSXString__Wrapper__>'?/g, '') - }; + return getJSXAttribute(propName, props[propName]); }); } -function formatPropValue(propValue) { +function getJSXAttribute(name, value) { + return { + name, + value: formatJSXAttribute(value) + .replace(/'?<__reactElementToJSXString__Wrapper__>/g, '') + .replace(/<\/__reactElementToJSXString__Wrapper__>'?/g, '') + }; +} + +function formatJSXAttribute(propValue) { if (typeof propValue === 'string') { return `"${propValue}"`; }