React: RenderHTML elements from text
How to render HTML elements from text in React? How to present them as HTML in the browser?
Solution:
The conversion of text to HTML in React can be done directly with dangerouslySetInnerHTML
Example React Code
render() { return ( <div dangerouslySetInnerHTML={{ __html: this.state.htmlcontent }} /> ); } |
This is how the conversion of text with HTML to HTML elements looks like in the browser
React Code: Read Data from Web API and Show in React Web Page
import React, { Component } from 'react'; import './Article.css'; import "bootstrap/dist/css/bootstrap.min.css";
export class Article extends Component { //--------< component: Article >--------
//----< compontent >---- static displayName = Article.name;
constructor(props) { //-< react: parameter > super(props); //-</ react: parameter > //--< react: variables >-- this.state = { idarticle: 0, loading: true, IDUser: "", title: "", TextContent: "", HtmlContent: "", Folder: "", Keywords: "", nImages: "", nVideos: "", nFiles: "", DtCreated: "", DtEdit: "" } }
//--< component.events >-- componentDidMount() { this.populateData(this.props.match.params.id); } //--</ component.events >-- //----</ compontent >----
//====< functions >====
//*load data from web api async populateData(id) { //--------< populateData() >-------- const response = await fetch('api/articles/' + id); //*get web_data from web api as json-string const data = await response.json(); //*convert json to data //console.log("this.state=" + this.state); //console.log(this.state);
this.setState(state => ({ idarticle :data.idArticle, iduser :data.idUser, title :data.title, textcontent :data.textContent, htmlcontent :data.htmlContent, folder :data.folder, keywords :data.keywords, nimages :data.nImages, nvideos :data.nVideos, nfiles :data.nFiles, dtcreated :data.dtCreated, dtedit :data.dtEdit, loading: false })); //*refresh state of arcticles //--------</ populateData() >-------- } //====</ functions >====
//====< HTML >==== //----< render >---- render() { //--------< render(HTML) >-------- return ( //----< return >---- <div className="submit-form"> { this.state.loading ? ( //--< IsLoading >-- <p>loading..</p> //--</ IsLoading >-- ) : ( //--< IsLoaded >-- <div> <p>IDArticle:{this.state.idarticle}</p> <p>Title{this.state.title}</p> <p>Folder{this.state.folder}</p> <p>Keywords{this.state.keywords}</p> <p>Date:{this.state.dtcreated}</p> <p>TextContent{this.state.textcontent}</p>
<p style={{ background: 'red' }}>HTML Content</p> <p>HTMLContent{this.state.htmlcontent}</p> <p style={{background: 'green'}}>HTML Content</p> <div dangerouslySetInnerHTML={{ __html: this.state.htmlcontent }} />
</div> //--</ IsLoaded >-- ) } </div> //----</ return >---- ); //--------</ render(HTML) >-------- } //----</ render >----
//====</ HTML >====
//--------</ component: Articles >-------- }
|
In Visual Studion Asp.Net Core Web API and Client App as React