I am new at reactjs and i want to manipulate styles directly with DOM or inline-styles. I am using useLayoutEffect
to make this run as early as possible.
import { useLayoutEffect } from 'react'
const App = () => {
useLayoutEffect(() => {
document.querySelector('.my-element').style.background = 'red'
}, [])
return <div className="my-element">Hello World!</div>
}
export default App
And the effect is runs like regular styles. But, am I doing the right thing? Or is there a better method for applying style directly with DOM?
And let's say I want to use it on server-side or static-side thing, I always has a slight FOUC (unstyled state) before the real styles is applied, like in NextJS for example.
Wanted to learn how to apply styles with DOM, in server-side, in SSG, and what the best way to do it.
I am new at reactjs and i want to manipulate styles directly with DOM or inline-styles. I am using useLayoutEffect
to make this run as early as possible.
import { useLayoutEffect } from 'react'
const App = () => {
useLayoutEffect(() => {
document.querySelector('.my-element').style.background = 'red'
}, [])
return <div className="my-element">Hello World!</div>
}
export default App
And the effect is runs like regular styles. But, am I doing the right thing? Or is there a better method for applying style directly with DOM?
And let's say I want to use it on server-side or static-side thing, I always has a slight FOUC (unstyled state) before the real styles is applied, like in NextJS for example.
Wanted to learn how to apply styles with DOM, in server-side, in SSG, and what the best way to do it.
Share Improve this question asked Nov 21, 2024 at 6:40 Santia FadiraSantia Fadira 1 1- 2 please check out Manipulating the DOM with Refs. React was made so devs can avoid working with DOM directly – Lã Ngọc Hải Commented Nov 21, 2024 at 6:44
1 Answer
Reset to default 0In React, prefer inline styles, CSS Modules, or CSS in JS like styled components for dynamic styling over direct DOM manipulation to avoid FOUC in SSR/SSG environments like Next.js
const App = () => {
const [backgroundColor, setBackgroundColor] = useState('red');
return (
<div style={{ background: backgroundColor }}>
Hello World!
</div>
);
};
CSS:
.myElement {
background: red;
}
JSX:
import styles from './App.module.css';
const App = () => (
<div className={styles.myElement}>Hello World!</div>
);
JSX:
import styled from 'styled-components';
const StyledDiv = styled.div`
background: red;
`;
const App = () => (
<StyledDiv>Hello World!</StyledDiv>
);