Here is my implementation using styled components with the version
"@types/styled-components": "^5.1.26"
and I'll provide you with an example of my code.
// index.tsx
import React, { useEffect, useState } from 'react';
import { ProfileHomeContainer } from './styled';
const ProfileHome: React.FC = () => {
const [test, setTest] = useState(false);
useEffect(() => {
const my = document.getElementById('test');
console.log(my);
console.log(test);
setTest(true);
}, [test]);
return (
<ProfileHomeContainer id='test' test={test ? 1 : 0}>
</ProfileHomeContainer>
)
}
// styled.ts
import styled from 'styled-components';
interface ProfileHomeContainerProps {
test: number;
}
const ProfileHomeContainer = styled.div<ProfileHomeContainerProps>`
display: flex;
align-items: center;
justify-content: center;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100vh;
background: rgba(0, 0, 0, 0.9);
z-index: 1101;
opacity: ${(props) => (props.test ? '1' : '0')};
transition: 1s;
`;
In addition to that, there are two global CSS classes for ProfileHomeContainer.
// which has opacity: 0
.KBlzF{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;position:fixed;top:0;left:0;width:100%;height:100vh;background:rgba(0,0,0,0.9);z-index:1101;opacity:0;-webkit-transition:1s;transition:1s;}
// has opacity: 1
.goFgwQ{display:-webkit-box;display:-webkit-flex;display:-ms-flexbox;display:flex;-webkit-align-items:center;-webkit-box-align:center;-ms-flex-align:center;align-items:center;-webkit-box-pack:center;-webkit-justify-content:center;-ms-flex-pack:center;justify-content:center;position:fixed;top:0;left:0;width:100%;height:100vh;background:rgba(0,0,0,0.9);z-index:1101;opacity:1;-webkit-transition:1s;transition:1s;}
Moreover, here are the console logs from my application:
<div id="test" class="sc-crXcEl goFgwQ"> // result of console.log(my)
false // result of console.log(test)
<div id="test" class="sc-crXcEl goFgwQ">
true
Now comes my question: Why does my component render with the class goFgwQ first? I expected it to be like this instead:
<div id="test" class="sc-crXcEl KBlzF">
false
<div id="test" class="sc-crXcEl goFgwQ">
true
This is because, during the initial run of useEffect, the state value for test is false
.
If you want to see more of my actual code, check out the GitHub links below: