0

I want to render react components with html, and my react component must listen states, but I can`t do it..

{component} = <span>ComponentText</span>

I have something like this and this Array can be in different orders and different combinations, for example:

let result = ['<div><p>123', {component}, '</p></div>', {component}];

With "dangerouslySetInnerHTML", I have:

123[Object][Object]

Without "dangerouslySetInnerHTML":

<div><p>123ComponentText</p></div>ComponentText

I`m looking for result like this:

123ComponentTextComponentText

And my states and events with this component must work well, Is it possible?

0

1 Answer 1

3

In React, you don't deal in HTML snippets like your result array, you deal in objects.

But you can use JSX to do something similar to what you want, just not with isolated bits of text in an array:

let result = [<div><p>123<Component /></p></div>, <Component />];

Live Example:

class Component extends React.Component {
  constructor(...args) {
    super(...args);
    this.state = {
      value: Math.floor(Math.random() * 1000)
    };
  }
  render() {
    return <span>I'm a component, this.state.value = {this.state.value}</span>;
  }
}

let result = [<div><p>123<Component /></p></div>, <Component />];

ReactDOM.render(
  <div>{result}</div>,
  document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

To illustrate that you're still dealing with objects despite using JSX, here's what that JSX transpiles to:

var result = [
    React.createElement(
        "div",
        null,
        React.createElement(
            "p",
            null,
            "123",
            React.createElement(Component, null)
        )
    ),
    React.createElement(Component, null)
];
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for quick answer! I receive string from server and after I add parts of my message together with components in one array.. Maybe in my case I need to write custom parser from string to react elements
@AlekseyDubinskiy: Yes, I'm afraid you do.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.