June.

10월 안에는 꼭...

Portfolio

About

React Fragment vs Null

2023/04/09
짧.

1 min read

React Fragment vs Null

Locales:

en

ko

Sometimes we use React Fragment and return null confusingly. Let's see the difference between the two.

Fragment

A Fragment is a component that you use to render your component. They don't create any unnecessary DOM elements when rendering a component. Fragments do not produce any output in HTML and can be used to group elements together without affecting the DOM structure.

1function ListComponent({ items }) { 2 return ( 3 <> 4 {items.map((item) => ( 5 <li key={item.id}>{item.name}</li> 6 ))} 7 </> 8 ); 9}

For example, when rendering a list component like the one above, you may want to render only the list items. You can use Fragments to render just the list items without creating unnecessary DOM elements.

return null

When a component returns null, it means it doesn't want to render anything. React will skip rendering this component and any children it may have. This can be useful when you want to conditionally render a component based on certain state or props.

1function ListComponent({ items }) { 2 if (items.length === 0) { 3 return null; 4 } 5 6 return ( 7 <> 8 {items.map((item) => ( 9 <li key={item.id}>{item.name}</li> 10 ))} 11 </> 12 ); 13}

When rendering a list component like the one above, sometimes you don't want to render anything when there are no list items. This can be accomplished by using return null.

Summary

  • return null: when it's really empty, and you don't want to render anything.
  • <></>: when you want to render a bunch of elements together without any additional HTML elements.

관련 포스트가 4개 있어요.

useSyncExternalStore가 무엇일까?

짧.
react-use-sync-external-store cover image
2023/10/23 (updated)

React 18 useSyncExternalStore에 대해서

CSS flex box의 align-items의 flex-start와 baseline의 차이점에 대해서

짧.
css-flex-box-align-items-attributes cover image
2023/09/24

CSS에서 align-items의 flex-start와 baseline의 차이점

React 18.0.0 react-dom의 flushSync의 사용법과 주의사항에 대해서 알아보자.

짧.
react-flush-sync cover image
2023/09/24

React flushSync에 대해서

maxLength를 넣고 이모지를 넣으면 브라우저마다 계산되는 것이 다르다.

짧.
html-input-max-length cover image
2023/09/15

HTML `<input />`의 maxLength 동작이 safari에서 다른 이슈

profile

정현수.

Currently Managed

Currently not managed

© 2024. junghyeonsu all rights reserved.