Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to transform plain text to html JSX in ReactJS

I have component like this:

import React from 'react';
import Autolinker from 'autolinker';

class Comment extends React.Component{

    constructor(props){
        super(props);
    }

    render(){
        return <li className="media comment">
            <div className="image">
                <img src={this.props.activity.user.avatar.small_url} width="42" height="42" />
            </div>
            <div className="body">
                <p>
                    <strong>{this.props.activity.user.full_name}</strong>
                </p>
            </div>
            <div>
                <p>
                    {Autolinker.link(this.props.activity.text)}
                </p>
            </div>
        </li>;
    }
}

export default Comment;

Autolinker returns me a string value like this:

"So basically <a href="http://www.silastar.com/dev-sila" target="_blank">silastar.com/dev-sila</a> is perfect and works correctly?"

How to convert this string to html JSX so that anchor link would appear as link not as plain text??

like image 486
zazmaister Avatar asked Aug 02 '15 13:08

zazmaister


People also ask

How is JSX converted to HTML in React?

JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement() and/or appendChild() methods. JSX converts HTML tags into react elements. You are not required to use JSX, but JSX makes it easier to write React applications.

How do I convert a string to JSX?

There're several ways to convert HTML Strings to JSX with React. One way is to put the string in between curly braces in our component. Another way is to put the string in an array with other strings or JSX code. Finally, we can use the dangerouslySetInnerHTML prop render an HTML string as HTML in our component.

Is JSX compiled into HTML?

JSX is a JavaScript Extension Syntax used in React to easily write HTML and JavaScript together. This is simple JSX code in React. But the browser does not understand this JSX because it's not valid JavaScript code. This is because we're assigning an HTML tag to a variable that is not a string but just HTML code.


1 Answers

You have to use dangerouslySetInnerHTML:

<p dangerouslySetInnerHTML={{__html: Autolinker.link(this.props.activity.text)}} />
like image 100
GJK Avatar answered Oct 05 '22 12:10

GJK