I wrote CSS. This works fine for blur.
document.addEventListener("click", () => {
document.querySelector(".transition").classList.toggle("blur");
})
.transition {
transition: 5s;
filter: blur(0px);
}
.blur {
filter: blur(5px);
}
<div class="transition">
TEXT
</div>
However, this will not work with React.js and Styled Components. I want to realize transition by filter without using add-on. Why doesn't this work, and how does it work?
const Button = styled.button``;
let ToggleBlurText = styled.div`
transition: "5s"
`;
function App() {
const [blur, setBlur] = useState(false);
useEffect(() => {
ToggleBlurText = styled.div`
filter: blur(${blur ? "0px" : "5px"});
transition: "5s"
`;
}, [blur]);
return (
<div className="App">
<ToggleBlurText>
<h2>TEXT</h2>
</ToggleBlurText>
<Button onClick={() => setBlur(!blur)}>button</Button>
</div>
);
}
That approach will not work. React probably won't re-render the ToggleBlurText
component and the styles inside the effect will not be applied.
Instead, you can create a styled component and toggle a css class that changes the blur depending on your state.
const Button = styled.button``;
const ToggleBlurText = styled.div`
transition: 5s;
filter: blur(0px);
&.blur {
filter: blur(5px);
}
`;
function App() {
const [blur, setBlur] = useState(false);
return (
<div className="App">
<ToggleBlurText className={blur ? 'blur' : ''}>
<h2>TEXT</h2>
</ToggleBlurText>
<Button onClick={() => setBlur(prev => !prev)}>button</Button>
</div>
);
}
I also fixed a typo in your styled component css and also changed the onClick handler slightly.