简体   繁体   中英

How to convert props.children to string in react js

I want to convert react children to string. In the below example I am passing div, h2 and p as children to Example in Exampleclass. when I call props.children in Example it returns an array but I need a props.children in the string format so that I can use it in dangerouslySetInnerHTML.

import React, { Component } from "react";
import Example from "./example";
export default class Exampleclass extends Component {
  render() {
    return (
      <div>
        <p>in class</p>
        <Example> // passing div, h2 and p as children to Example
          <div>
          <h2>function</h2>
          <p>function</p>
          </div>
        </Example>
      </div>
    );
  }
}
import React from "react";

export default function example(props) {
  console.log("child", props.children); // returns array  but i need <div><h2>function</h2><p>function</p></div> here

  return <div dangerouslySetInnerHTML={{ __html: `${props.children}` }} />;    // returns [object Object]

}

It would be difficult to transform children object into some kind of a flat string with a JSX-a-like structure. children is a complex object with a lot of nested fields. You would have to convert it firstly to an array , then iterate over it, probably recursively, pick correct props and so on.

However you could pass your children not as a children , but as a separate prop.

 const Child = ({ child }) => { return <div dangerouslySetInnerHTML={{ __html: child }} />; }; const App = () => { const data = ` <div> <h2>function</h2> <p>function</p> </div> `; return <Child child={data} /> }; ReactDOM.render(<App />, document.getElementById("root"));
 <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root"></div>

Edit : You could, however, use renderToStaticMarkup function, but it will render only pure html (it will compile components into html). In your example you are passing only html elements so I guess it would be okey.

const markup = ReactDOMServer.renderToStaticMarkup(children);

return <div dangerouslySetInnerHTML={{ __html: markup }} />;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM