I am parsing a HTML string to React.js and render it as HTML element using "ReactHtmlParser" suggested in that previous post React.js: Raw HTML string does not gets recognized as HTML elements from Node.js. Now, I am trying add Bootstrap style attribute on it, by doing the following:
app.get('/myCart', (req, res) => {
var data;
var htmlString ="";
var total = 0;
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("cart");
dbo.collection("items").find().toArray(function(err, result) {
if (err) throw err;
console.log("here")
data = result
for(let item of data){
htmlString += "<div className=\"row\"><div className=\"col\">" + item.desc + "</div>" + "<div className=\"col\">" + item.price + "</div></div>"
total += item.price
}
console.log("total is" + total)
htmlString +="<div className=\"row\"><div>" + total + "</div><div>"
console.log(htmlString)
res.send({express: htmlString})
db.close();
});
});
My render method:
render(){
console.log(this.state.cartData)
return(
<div className="col">
<div>{ReactHtmlParser(this.state.cartData)}</div>
</div>
)
}
As you can see, it is actually className
not classname
. However, when I render it to front-end, it got error saying that Invalid DOM property classname. Did you mean className
I really have no idea because I only put className as attribute. Does it have to do with ReactHtmlParser?
I am parsing a HTML string to React.js and render it as HTML element using "ReactHtmlParser" suggested in that previous post React.js: Raw HTML string does not gets recognized as HTML elements from Node.js. Now, I am trying add Bootstrap style attribute on it, by doing the following:
app.get('/myCart', (req, res) => {
var data;
var htmlString ="";
var total = 0;
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("cart");
dbo.collection("items").find().toArray(function(err, result) {
if (err) throw err;
console.log("here")
data = result
for(let item of data){
htmlString += "<div className=\"row\"><div className=\"col\">" + item.desc + "</div>" + "<div className=\"col\">" + item.price + "</div></div>"
total += item.price
}
console.log("total is" + total)
htmlString +="<div className=\"row\"><div>" + total + "</div><div>"
console.log(htmlString)
res.send({express: htmlString})
db.close();
});
});
My render method:
render(){
console.log(this.state.cartData)
return(
<div className="col">
<div>{ReactHtmlParser(this.state.cartData)}</div>
</div>
)
}
As you can see, it is actually className
not classname
. However, when I render it to front-end, it got error saying that Invalid DOM property classname. Did you mean className
I really have no idea because I only put className as attribute. Does it have to do with ReactHtmlParser?
Share Improve this question asked Sep 28, 2018 at 15:43 Spencer OvetskySpencer Ovetsky 1701 gold badge6 silver badges14 bronze badges 9-
what if you change it to
class
? – Jonas Wilms Commented Sep 28, 2018 at 15:46 - It would be wrong because react use className as its default attribute – Spencer Ovetsky Commented Sep 28, 2018 at 15:46
-
just try out
class
... I got the feeling that it might work – Jonas Wilms Commented Sep 28, 2018 at 15:47 - 1 its HTML string so you just write there class instead of className – Arif Rathod Commented Sep 28, 2018 at 15:47
- How are you fetching the code from the backend? – epascarello Commented Sep 28, 2018 at 15:48
2 Answers
Reset to default 5TheReactHTMLParser parses HTML, so you have to use the HTML class
property.
If you use className
, the parser will lowercase the properties as html props are always lowercase, resulting in the error you get.
You can check this document (https://reactjs/docs/dom-elements.html), React DOM
is not HTML DOM
will have some difference in attribute name like className
in React DOM vs class
in HTML DOME
All Supported HTML Attributes As of React 16, any standard or custom DOM attributes are fully supported.
React has always provided a JavaScript-centric API to the DOM. Since React ponents often take both custom and DOM-related props, React uses the camelCase convention just like the DOM APIs:
<div tabIndex="-1" /> // Just like node.tabIndex DOM API <div className="Button" /> // Just like node.className DOM API <input readOnly={true} /> // Just like node.readOnly DOM API
These props work similarly to the corresponding HTML attributes, with the exception of the special cases documented above.
Some of the DOM attributes supported by React include:
accept acceptCharset accessKey action allowFullScreen alt async autoComplete autoFocus autoPlay capture cellPadding cellSpacing challenge charSet checked cite classID className colSpan cols content contentEditable contextMenu controls controlsList coords crossOrigin data dateTime default defer dir disabled download draggable encType form formAction formEncType formMethod formNoValidate formTarget frameBorder headers height hidden high href hrefLang htmlFor httpEquiv icon id inputMode integrity is keyParams keyType kind label lang list loop low manifest marginHeight marginWidth max maxLength media mediaGroup method min minLength multiple muted name noValidate nonce open optimum pattern placeholder poster preload profile radioGroup readOnly rel required reversed role rowSpan rows sandbox scope scoped scrolling seamless selected shape size sizes span spellCheck src srcDoc srcLang srcSet start step style summary tabIndex target title type useMap value width wmode wrap
Similarly, all SVG attributes are fully supported:
accentHeight accumulate additive alignmentBaseline allowReorder alphabetic amplitude arabicForm ascent attributeName attributeType autoReverse azimuth baseFrequency baseProfile baselineShift bbox begin bias by calcMode capHeight clip clipPath clipPathUnits clipRule colorInterpolation colorInterpolationFilters colorProfile colorRendering contentScriptType contentStyleType cursor cx cy d decelerate descent diffuseConstant direction display divisor dominantBaseline dur dx dy edgeMode elevation enableBackground end exponent externalResourcesRequired fill fillOpacity fillRule filter filterRes filterUnits floodColor floodOpacity focusable fontFamily fontSize fontSizeAdjust fontStretch fontStyle fontVariant fontWeight format from fx fy g1 g2 glyphName glyphOrientationHorizontal glyphOrientationVertical glyphRef gradientTransform gradientUnits hanging horizAdvX horizOriginX ideographic imageRendering in in2 intercept k k1 k2 k3 k4 kernelMatrix kernelUnitLength kerning keyPoints keySplines keyTimes lengthAdjust letterSpacing lightingColor limitingConeAngle local markerEnd markerHeight markerMid markerStart markerUnits markerWidth mask maskContentUnits maskUnits mathematical mode numOctaves offset opacity operator order orient orientation origin overflow overlinePosition overlineThickness paintOrder panose1 pathLength patternContentUnits patternTransform patternUnits pointerEvents points pointsAtX pointsAtY pointsAtZ preserveAlpha preserveAspectRatio primitiveUnits r radius refX refY renderingIntent repeatCount repeatDur requiredExtensions requiredFeatures restart result rotate rx ry scale seed shapeRendering slope spacing specularConstant specularExponent speed spreadMethod startOffset stdDeviation stemh stemv stitchTiles stopColor stopOpacity strikethroughPosition strikethroughThickness string stroke strokeDasharray strokeDashoffset strokeLinecap strokeLinejoin strokeMiterlimit strokeOpacity strokeWidth surfaceScale systemLanguage tableValues targetX targetY textAnchor textDecoration textLength textRendering to transform u1 u2 underlinePosition underlineThickness unicode unicodeBidi unicodeRange unitsPerEm vAlphabetic vHanging vIdeographic vMathematical values vectorEffect version vertAdvY vertOriginX vertOriginY viewBox viewTarget visibility widths wordSpacing writingMode x x1 x2 xChannelSelector xHeight xlinkActuate xlinkArcrole xlinkHref xlinkRole xlinkShow xlinkTitle xlinkType xmlns xmlnsXlink xmlBase xmlLang xmlSpace y y1 y2 yChannelSelector z zoomAndPan
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744221036a4563782.html
评论列表(0条)