๐Ÿ’ป Fragments(feat. ๋ฆฌ์•กํŠธ ๊ณต์‹๋ฌธ์„œ)

waterglassesยท2022๋…„ 11์›” 9์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
45/50
post-thumbnail

โš ๏ธ ์ •๋ฆฌํ•œ ๋‚ด์šฉ์€ ์˜คํƒ€๋‚˜ ์ž˜๋ชป๋œ ์ •๋ณด๊ฐ€ ์žˆ์„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋Œ“๊ธ€๋กœ ์•Œ๋ ค์ฃผ์‹œ๋ฉด ๊ฐ์‚ฌํ•˜๊ฒ ์Šต๋‹ˆ๋‹ค.

Fragment

Fragments๋Š” DOM์— ๋ณ„๋„์˜ ๋…ธ๋“œ๋ฅผ ์ถ”๊ฐ€ํ•˜์ง€ ์•Š๊ณ  ์—ฌ๋Ÿฌ ์ž์‹์„ ๊ทธ๋ฃนํ™”ํ•  ์ˆ˜ ์žˆ๋‹ค.

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}

<React.Fragment>๋ฅผ <> ๋‹จ์ถ• ๋ฌธ๋ฒ•์œผ๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

๋™๊ธฐ

class Table extends React.Component {
  render() {
    return (
      <table>
        <tr>
          <Columns />
        </tr>
      </table>
    );
  }
}

๋ Œ๋”๋ง ๋œ HTML์ด ์œ ํšจํ•˜๋ ค๋ฉดย <Columns />๊ฐ€ ์—ฌ๋Ÿฌย <td>ย ์—˜๋ฆฌ๋จผํŠธ๋งŒ ๋ฐ˜ํ™˜ํ•ด์•ผ ํ•œ๋‹ค. <Columns />
์˜ย render()ย ์•ˆ์— ๋ถ€๋ชจ div๋กœ ์ž์‹๋“ค์„ ๊ฐ์‹ผ๋‹ค๋ฉด ๋ Œ๋”๋ง ๋œ HTML์€ ์œ ํšจํ•˜์ง€ ์•Š๋Š”๋‹ค.

class Columns extends React.Component {
  render() {
    return (
      <div>
        <td>Hello</td>
        <td>World</td>
      </div>
    );
  }
}

์ด๋Ÿฐ ๋ฌธ์ œ๋ฅผ Fragments๋Š” ์•„๋ž˜์ฒ˜๋Ÿผ ํ•ด๊ฒฐํ•ด์ค€๋‹ค.

class Columns extends React.Component {
  render() {
    return (
      <React.Fragment>
        <td>Hello</td>
        <td>World</td>
      </React.Fragment>
    );
  }
}

๋‹จ์ถ• ๋ฌธ๋ฒ•

๋นˆ ํƒœ๊ทธ์ฒ˜๋Ÿผ Fragments๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜๋„ ์žˆ๋‹ค.

keyย ๋˜๋Š” ์–ดํŠธ๋ฆฌ๋ทฐํŠธ๋ฅผ ์ง€์›ํ•˜์ง€ ์•Š๋Š”๋‹ค๋Š” ๊ฒƒ์„ ๋นผ๊ณ  ๋‹ค๋ฅธ ์—˜๋ฆฌ๋จผํŠธ์ฒ˜๋Ÿผย <></>์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.****

key๊ฐ€ ์žˆ๋Š” Fragments

Fragments์—ย key๊ฐ€ ์žˆ๋‹ค๋ฉดย <React.Fragment>ย ๋ฌธ๋ฒ•์œผ๋กœ ๋ช…์‹œ์ ์œผ๋กœ ์„ ์–ธํ•ด์•ผ ํ•œ๋‹ค.

function Glossary(props) {
  return (
    <dl>
      {props.items.map(item => (
        // React๋Š” `key`๊ฐ€ ์—†์œผ๋ฉด key warning์„ ๋ฐœ์ƒํ•ฉ๋‹ˆ๋‹ค.
        <React.Fragment key={item.id}>
          <dt>{item.term}</dt>
          <dd>{item.description}</dd>
        </React.Fragment>
      ))}
    </dl>
  );
}

key๋Š”ย Fragment์— ์ „๋‹ฌํ•  ์ˆ˜ ์žˆ๋Š” ์œ ์ผํ•œ ์–ดํŠธ๋ฆฌ๋ทฐํŠธ์ด๋‹ค.

๐Ÿ”ฅ ๋Š๋‚€์ 

fragments๋Š” ์ •๋ง ์ž์ฃผ ์“ฐ์ด๊ณ  ๊ทธ๋™์•ˆ ๋งŽ์ด ์‚ฌ์šฉํ•ด๋ณด์•˜๊ธฐ ๋•Œ๋ฌธ์— ์ต์ˆ™ํ•˜์˜€๋‹ค.

Refer

profile
๋งค ์ˆœ๊ฐ„ ์„ฑ์žฅํ•˜๋Š” ๊ฐœ๋ฐœ์ž๊ฐ€ ๋˜๋ ค๊ณ  ๋…ธ๋ ฅํ•˜๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.

0๊ฐœ์˜ ๋Œ“๊ธ€