Riccardo
Riccardo

Reputation: 35

Render an Element with React

Honestly I don't think that this is the best Title, but I've no idea how explain it.

So sorry for it.

I'm trying to write a Component that parse all links(thar are not into a anchor tag) and emoji and render it like links or image.

For emoji I'm using this amazing component: https://github.com/banyan/react-emoji

It works well, but the problem is with the simple links...I don't have found a way for render it like links, instead of text of the link tag.

This is my code:

# @cjsx React.DOM

@Linkify = React.createClass
  displayName: 'Linkify'

  mixins: [ReactEmoji]

  componentDidMount: ->  

  componentWillUnmount: ->

  render: ->

    <div>
      {@parseLinks(@props.text)}
    </div>

  parseLinks: (text) ->
    pattern = /(ht|f)tps?:\/\/[^\"<]*?(?=\s|$|<\/[^a]>)/gi
    results = text.match(pattern)
    new_text = text
    if results and results.length > 0
      for result in results
        link_html = React.createElement('a', {href: result}, result)
        new_text = new_text.replace(result, link_html)
    return @emojify(new_text)

and if I wrote:

Hello search here google.com :)

I get: Hello search here [object Object] :) (instead of :) I've the correct emoji image)

The problem is: why it don't show correctly the Object Link ? where I done wrong ?

Thanks for any help.

Upvotes: 1

Views: 6229

Answers (1)

Michelle Tilley
Michelle Tilley

Reputation: 159095

link_html = React.createElement('a', {href: result}, result)
new_text = new_text.replace(result, link_html)

You can't use String#replace to put an object (returned by React.createElement) into a string. It's like saying

var text = "one two three";
var el = {testing: true};
alert(text.replace("two", el));

Instead, you should return a ReactElement (created with JSX or React.createElement) that contains the associated text, but with the link in the correct place in the children.

Consider the output of

<span>Test <a href="google.com">google.com</a> link</span>

which is

React.createElement("span", null,
  "Test ",
  React.createElement("a", {href: "google.com"},
    "google.com"
  ), 
  " link"
)

Upvotes: 6

Related Questions