0

Given existing html.

<component text="one"><h1>First Component</h1></component>
<component text="two"><h1>Second Component</h1></component>
<component text="three"><h2>Third Component</h2></component>

I wish to wrap these components in a react class, that obtains the text property from the existing DOM. In addition, the existing markup should be rendered inside the component.

I have a partially working solution:

import * as React from "react";
import * as DOM from "react-dom";
import $ from "jquery";

export interface IWellProps {
    text: string
}

export class Well extends React.Component<IWellProps, {}> {
    render() {
        return <div>
            <span>{this.props.text}</span>
            <div>{this.props.children}</div>
        </div>;
    }
}

$("component")
    .each((i, e) => {
        DOM.render(<Well text={$(e).attr("text")}>{$(e).html()}</Well>, e);
        // version below renders html... the above does not.
        // is there not an api to convert text into `react.createElement` calls
        // DOM.render(<Well text={$(e).attr("text")}><h1>test</h1></Well>, e);
    });

My current implementation partially works, but uses a jquery hack? to create the components. I have a hunch that there will be some blowback when the components start using events and other react complexities.

  • The text property is rendered from the original html as expected.
  • The inner html is rendered as text not html.

enter image description here

Jim
  • 14,952
  • 15
  • 80
  • 167
  • Duplicated?http://stackoverflow.com/a/29189660/1181036 – Lucas Katayama Nov 17 '16 at 06:36
  • I don't think so, no. I am using `this.props.children` **not** `dangerouslySetInnerHTML`, besides that, why should it make a difference, the html I am attempting to insert is inside the JSX (it is not text), if I added the markup manually, instead of using `{$(e).html()}` would it not render as `HTML`? – Jim Nov 17 '16 at 06:39
  • I am also asking if there is a better pattern for rendering the components besides using jquery? – Jim Nov 17 '16 at 06:43
  • `DOM.render(

    TEST

    , e);` renders as HTML, so how do I replace `

    TEST

    ` with the original nodes as I am attempting to do?
    – Jim Nov 17 '16 at 06:46

0 Answers0