reactjs datagrid use html

1k views Asked by At

Im using the datagrid component here

I would like to use html in one of the fields and show a link or a picture etc. I tried using the render function for the column as below

var columns = [
    { name = 'field' },
    { name = 'link',render : function(uri) { return '<a href="'+uri+'">link</a>'} },
];

however it prints out the html as text

2

There are 2 answers

3
gcedo On

This is because by default React escapes HTML, in order to prevent XSS attacks. You can by pass this, by using the prop dangerouslySetInnerHTML, as described here.

However, as the name suggests, this leads to a vulnerability. I would suggest instead to use Mardown, especially the marked package.

You can write a general component like this one and then use it everywhere.

import React from 'react';
import marked from 'marked';

const Markdown = React.createClass({
    render() {
        const raw = marked(this.props.text, {sanitize: true});
        return  <span dangerouslySetInnerHTML={{__html: rawMarkup}} />;
    }

});

In your case then

var columns = [
    { name = 'field' },
    { name = 'link', render : function(uri) { return <Markdown text={'[link](' + uri + ')'} />} },
];
0
arkoak On

First I created a class which will output a link

var Linkify = React.createClass({
    render : function(){
        return (
             <a href={this.props.link}>{this.props.title}</a>
       )
   },
});

Then used this class in the render function

 var columns = [
{ name : 'edit', render : function(id){
        var editlink = "http://www.example.com/id="+id;
        return ( <Linkify link={editlink} title="edit" />)
    }  
},

This way any html can be used in the datagrid column by simply using the react component.