最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to apply styles with DOM in ReactJS and server-side framework? - Stack Overflow

programmeradmin1浏览0评论

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
Add a comment  | 

1 Answer 1

Reset to default 0

In 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>
);
发布评论

评论列表(0)

  1. 暂无评论