We want to hear from you!Take our 2021 Community Survey!
Support Ukraine ๐Ÿ‡บ๐Ÿ‡ฆ Help Provide Humanitarian Aid to Ukraine.

Fragments

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

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

์ด๋ฅผ ์„ ์–ธํ•˜๋Š” ์ƒˆ๋กœ์šด ๋‹จ์ถ• ๋ฌธ๋ฒ•์ด ์žˆ์Šต๋‹ˆ๋‹ค.

๋™๊ธฐ

์ปดํฌ๋„ŒํŠธ๊ฐ€ ์—ฌ๋Ÿฌ ์ž์‹์„ ๋ฐ˜ํ™˜ํ•˜๋Š” ๊ฒƒ์€ ํ”ํ•œ ํŒจํ„ด์ž…๋‹ˆ๋‹ค. ๋‹ค์Œ React ์˜ˆ์‹œ๋ฅผ ๋ณด์„ธ์š”.

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>
    );
  }
}

<Table />์˜ ์ถœ๋ ฅ ๊ฒฐ๊ณผ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์Šต๋‹ˆ๋‹ค.

<table>
  <tr>
    <div>
      <td>Hello</td>
      <td>World</td>
    </div>
  </tr>
</table>

Fragments๋Š” ์ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•ด์ค๋‹ˆ๋‹ค.

์‚ฌ์šฉ๋ฒ•

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

์˜ฌ๋ฐ”๋ฅธ <Table />์˜ ์ถœ๋ ฅ ๊ฒฐ๊ณผ๋Š” ์•„๋ž˜์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

<table>
  <tr>
    <td>Hello</td>
    <td>World</td>
  </tr>
</table>

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

Fragments๋ฅผ ์„ ์–ธํ•˜๋Š” ๋” ์งง๊ณ  ์ƒˆ๋กœ์šด ๋ฌธ๋ฒ•์ด ์žˆ์Šต๋‹ˆ๋‹ค. ๋งˆ์น˜ ๋นˆ ํƒœ๊ทธ์™€ ๊ฐ™์Šต๋‹ˆ๋‹ค.

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

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

key๊ฐ€ ์žˆ๋Š” Fragments

Fragments์— key๊ฐ€ ์žˆ๋‹ค๋ฉด <React.Fragment> ๋ฌธ๋ฒ•์œผ๋กœ ๋ช…์‹œ์ ์œผ๋กœ ์„ ์–ธํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ์ •์˜ ๋ชฉ๋ก์„ ๋งŒ๋“ค๊ธฐ ์œ„ํ•ด ์ปฌ๋ ‰์…˜์„ fragments ๋ฐฐ์—ด๋กœ ๋งคํ•‘ํ•˜๋Š” ์‚ฌ์šฉ ์‚ฌ๋ก€์ž…๋‹ˆ๋‹ค.

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์— ์ „๋‹ฌํ•  ์ˆ˜ ์žˆ๋Š” ์œ ์ผํ•œ ์–ดํŠธ๋ฆฌ๋ทฐํŠธ์ž…๋‹ˆ๋‹ค. ์ถ”ํ›„ ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ์™€ ๊ฐ™์€ ์ถ”๊ฐ€์ ์ธ ์–ดํŠธ๋ฆฌ๋ทฐํŠธ๋ฅผ ์ง€์›ํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค.

๋ผ์ด๋ธŒ ๋ฐ๋ชจ

CodePen์—์„œ ์ƒˆ๋กœ์šด JSX fragment ๋ฌธ๋ฒ•์„ ์‚ฌ์šฉํ•ด ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

Is this page useful?Edit this page