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??
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.
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.
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.
You have to use dangerouslySetInnerHTML:
<p dangerouslySetInnerHTML={{__html: Autolinker.link(this.props.activity.text)}} />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With