/* In a CSS file */.my-class {
background-color: red;
font-size: 16px;
}
// Inline styling in JavaScriptconst element = document.getElementById('myElement');
element.style.backgroundColor = 'red';
element.style.fontSize = '16px';
TS에서는 다른 타입을 사용하는 방법을 통해 이를 구별한다.
일반적인 css 속성은 => CSSStyleDeclaration 타입을 가지며, DOM요소의 style 속성에서 발견 할 수 있다.
const styles: CSSStyleDeclaration = document.body.style;
styles.setProperty("background-color", "red");
const style: React.CSSProperties = {
backgroundColor: "red",
fontSize: "16px",
};
Emotion 또는 기타 CSS-in-JS 라이브러리에서 사용되는 타입이다
동적 스타일을 위해 CSS를 문자열로 인코딩한다.
import { css } from "@emotion/react";
const myStyle = css`
background-color: red;
font-size: 16px;
`;
https://codefrontend.com/resize-observer-react/
window에서는 resize 이벤트가 있어서 윈도우 사이즈의 변화를 브라우저에서 감지 할 수 있다.
하지만 특정 DOM 요소의 size 변화를 감지하기 위해서는 ResizeObserver API를 이용해 특정 element를 tracking 하는 과정이 필요하다.
React에서는 이를 hook으로 만들어 로직을 재사용 할 수 있다.
자세한 내용은 위의 링크를 참조하자
import { useLayoutEffect, useRef } from 'react';
function useResizeObserver<T extends HTMLElement>(
callback: (target: T, entry: ResizeObserverEntry) => void
) {
const ref = useRef<T>(null)
useLayoutEffect(() => {
const element = ref?.current;
if (!element) {
return;
}
const observer = new ResizeObserver((entries) => {
callback(element, entries[0]);
});
observer.observe(element);
return () => {
observer.disconnect();
};
}, [callback, ref]);
return ref
}
export default useResizeObserver;
- link
let value = null ?? 123; => value === 123
let value = 0 ?? 2 => value === 0
let value = null || 123; => value === 123
let value = 0 || 2 => value === 2
코드적인 관점으로 봤을 때 => null, undefined에 대해서만 기본값을 제공해야하면 ?? 를 사용하는게 맞다.
기본값 사용은 지양해야하는데, 잘못된 데이터가 표출되기 때문 + 없으면 에러를 뱉는것이 맞다.
https://www.linkedin.com/pulse/stop-using-inline-styles-react-js-azeem-aleem/
react에서 style 객체에 인라인 객체형태로 스타일을 넣는 것을 지양해야 한다.
불필요한 렌더링을 유발하기 때문.