I have a simple React component (some randomly placed “stars”) that does not want to keep inline styling when navigating around my app – specifically the transform
property is removed (see screenshots below). Reloading the page will add the transform
params I feed it but will delete it, again, when navigating.
const stars = [
{
s: 1.01008930445147,
curR: 1012.8646405396803,
yRotate: 82.08700538334165,
xRotate: -34.590599732775004,
bgColor: 'yellow'
},
{
s: 0.6837385344214948,
curR: 968.297526216683,
yRotate: 17.954768821347578,
xRotate: -45.47975056098913,
bgColor: 'blue'
},
{
s: 0.8286765657990229,
curR: 1598.3185292691123,
yRotate: 196.0609316224604,
xRotate: -9.90854666326314,
bgColor: 'green'
},
]
function Stars() {
return (
<>
{stars.map((star) => {
return (
<div
className="star"
style={{
transform:
" translate3d(0,0,-" +
star.curR +
"px) rotateY(" +
star.yRotate +
"deg) rotateX(" +
star.xRotate +
"deg) scale(" +
star.s +
");",
transformOrigin: "0 0 " + star.curR + "px",
backgroundColor: star.bgColor,
}}
></div>
);
})}
</>
);
}
export default SomeParentComponent() {
return (
<div className="stars">
<Stars/>
</div>
);
}
.stars {
height: 100%;
width: 100%;
position: absolute;
z-index: 3;
top: 0;
left: 0;
transform: perspective(500px);
transform-style: preserve-3d;
position: absolute;
perspective-origin: 50% 100%;
.star {
position: absolute;
top: 50%;
left: 50%;
transform-origin: 0 0 -300px;
transform: translate3d(0, 0, -300px) translate(-50% -50%);
backface-visibility: hidden;
background-color: $off-white;
height: 3px;
width: 3px;
border-radius: 99px;
z-index: 5;
}
}
Screenshot of code on initial load
Screenshot of code after navigating within app
I added bgColor
after the transform
for testing, thinking react was removing anything after the transform-origin
property but, no, it only removes transform
styling.
I haven’t really delved into workarounds – I think I can force it to re-render, but want to understand why transform
doesn’t work.
Some notes:
-
The original
stars
object contains 700 items; I thought referencing such a large object was the culprit but I shortened it to three items and it’s still not working. -
I’m using Next.js and the Pages Router
sucrete is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.