Ajouve
Ajouve

Reputation: 10089

Inject dynamic content react

I want to display content from my database into a react component. The content can be a string or html, I know React don't really like html injections ...

I write a module but it's not working as I want

import $ from "jquery";
import React from 'react'

export default React.createClass({

  getInitialState() {
    return { content: [] };
  },

  componentDidMount: function() {

    if (this.state.content.length == 0) {
      $.get('/content', function(data) {
        this.setState({
          content: data
        })
      }.bind(this))
    }

  },

  getValue() {

    for (let i = 0; i < this.state.content.length; i++) {
      if (this.state.content[i].key == this.props.contentKey) {
        return this.data[i].value;
      }
    }

    return this.props.contentKey;
  },

  render() {
    return (<span>{this.getValue()}</span>)
  }
})

this one will convert <Content contentKey="key"/> into <span>value</span>

I'd like for example

render() {
    return (
        <div>
            {content('key1')}
            <img src={content('key2')} />
        </div>
    )
}

let's say my server returns

{"key1": "<p>I am key 1 value</p>", "key2": "key2Value.jpg"}

The result should be something like

<div>
    <p>I am key 1 value</p>
    <img src="key2Value.jpg" />
</div>

And I don't want the html to be escaped

Upvotes: 2

Views: 3997

Answers (2)

Doukeshi
Doukeshi

Reputation: 11

You could use XHR instead of jquery.

var xhr = new XMLHttpRequest()
xhr.open("GET", './a.json', true)

with a callback in

xhr.onloadend()

but you would need

dangerouslySetInnerHTML={{ __html: content}}

Upvotes: 1

Isaiah Lee
Isaiah Lee

Reputation: 448

What would work is to create a class method such as below:

renderEls() {
  return this.state.content.map(function(el) {
    return (<div>
      <p>{el.key1}</p>
      <img src={el.key2} />
    </div>) 
  });
}

Then, in your component's render method, you'd want to do something like this:

render() {
  return <div>{this.renderEls()}</div>
}

Also, if you're going to be using React, it's generally best to split up everything into their own separate components.

In your case, it might not be a bad idea to create a new component that you'll render for each object returned from the server, passing in the values as props.

To render HTML from a string, React gives you a way to do so as outlined here: https://facebook.github.io/react/tips/dangerously-set-inner-html.html

Hope that helps!

Upvotes: 2

Related Questions