score:1

Accepted answer
const MyComponent = ({
  title
}) => (
  <div>{title}</div>
)

const MyDoc = () => (
  <Code>
    <MyComponent title="My title" obj={{obj: {obj: 1}}}>
      <MyComponent title="My another component title">
        <MyComponent title="My another component title" />
      </MyComponent>
    </MyComponent>
  </Code>
)

const Code = ({
  children
}) => (
  <div>
    {children}
    <pre><code>
      {JsxString(children)}
      </code></pre>
  </div>
)

const JsxString = (component, counter = 0) => {
  let type = component.type.name;
  let props = component.props;
  let propsString = "";
  for (let key in props) {
    if (key !== "children") {
      let propValue = props[key];
      let value = "";
      if (propValue instanceof Object) {
        value = `{${JSON.stringify(propValue).replace(/['"]+/g, '')}}`;
      } else {
        value = `"${propValue}"`;
      }
      propsString += ` ${key}=${value}`;
    }
  }
  if (props.children) {
    counter += 2;
    var children = JsxString(props.children, counter);
    return `<${type}${propsString}>
${Array(counter).join(" ")}  ${children}
${Array(counter).join(" ")}</${type}>`;
  }
  return `<${type}${propsString} />`;
}

ReactDOM.render(
  <MyDoc />,
  document.getElementById('container')
);

Related Query

More Query from same tag