Hello everyone!
This might be a silly question but I can't figure out why the className variable in the console.log has a different value from the one used in the className attribute of the <p>
.
I'm trying to generate random class names for HTML tags so then I can create CSSStyleSheets with rules to these HTML tags. Since, in this example, the css prop is the same the styling is working but the className variables in the tag and in console.log are different and that's what I can't understand why.
Am I missing something obvious or is this somehow the intended behaviour?
The code is this:
import React from 'react'
const constructCss = (css) => {
const style = document.createElement('style')
document.head.appendChild(style)
style.appendChild(document.createTextNode(css))
}
const constructCssStyleAndReturnClassName = (css) => {
const generateRandomString = (length=6) => Math.random().toString(20).substr(2, length)
const className = `styled-${generateRandomString(8)}`
constructCss(`.${className} ${css}`)
return className
}
const Pa = ({css, children}) => {
const className = constructCssStyleAndReturnClassName(css)
console.log('Rendering with className: ', className)
return <p className={className}>{children}</p>
}
export default function App() {
return (
<div className="App">
<Pa css={`{ background-color: blue; color: white }`}>Helloooooo</Pa>
</div>
);
}
It's also here in codesandbox
Thanks in advance :)
question from:
https://stackoverflow.com/questions/65847325/problems-generating-random-classnames-for-html-tags-in-react 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…