I want to create a comment section for my websites ( actually it's not relevant to the question but helps to understand the code). I defined a String named CommentsListText that contains all the comments and now I want to add this to the returned component . How can I do that ?
import React from 'react';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import ListItemText from '@material-ui/core/ListItemText';
import Checkbox from '@material-ui/core/Checkbox';
import Avatar from '@material-ui/core/Avatar';
import Paper from '@material-ui/core/Paper';
import CommentTextTemplate from './CommentTextTemplate';
import Grid from '@material-ui/core/Grid';
import {connect} from 'react-redux';
import {fetchCommentsWithRedux} from '../../actions/FetchComments';
class CommentsList extends React.Component {
componentDidMount(){
this.props.fetchCommentsWithRedux(this.props.courseId,this.props.option);
}
render() {
const { classes,comments } = this.props;
let commentsListText = "";
var i;
let comment;
for (i=0;i<comments.length;i++){
comment = comments[i];
if(!!comment.parent_id){
continue;
}
commentsListText +="<Grid item className={classes.commentL1} >"+
"<Paper className={classes.commentL1Paper} >"+
"<ListItem dense className={classes.listItem}>"+
'<Avatar alt="phebie boffei" src="/src/public/avatar.jpg" className={classes.commentAvatar}/>'+
'<CommentTextTemplate/>'+
"</ListItem>";
let innerCommentsList = comments.find((singleComment)=>{
return singleComment.parent_id == i;
})
var j;
if(!!innerCommentsList){
for (j=0;j<innerCommentsList.length;i++){
let singleInnerComment = innerCommentsList[j];
commentsListText +="<Grid item className={classes.commentL1} >"+
"<Paper className={classes.commentL1Paper} >"+
"<ListItem dense className={classes.listItem}>"+
'<Avatar alt="phebie boffei" src="/src/public/avatar.jpg" className={classes.commentAvatar}/>'+
'<CommentTextTemplate/>'+
"</ListItem></Paper></Grid>";
}
}
commentsListText +='</Paper></Grid>';
// commentsListText = "<Grid><ListItem >hamid karami sarini</ListItem></Grid>"
// console.log(commentsListText);
}
return (
<List>
{/* Here I want to show the comments List. */}
{/* <div dangerouslySetInnerHTML={{ __html: commentsListText }} /> */}
</List>
);
}
}
const mapStateToProps = ({Comments}) => {
return Comments;
};
export default withStyles(styles)(connect(mapStateToProps,{fetchCommentsWithRedux})(CommentsList));
the solution I found was to use :
<div dangerouslySetInnerHTML={{ __html: commentsListText }} />
but this just works on html tags. How do i Convert my string to React Component?