๐ŸŒฑ → ๐ŸŒณ

[React] React.Fragment ๋ณธ๋ฌธ

Client/React

[React] React.Fragment

BAY 2022. 9. 30. 18:33
728x90

React.Fragment

์‹ค์ œ ๋ฆฌ์•กํŠธ์—์„œ ์ปดํฌ๋„ŒํŠธ๋ฅผ ์กฐํ•ฉํ•  ๋•Œ, ์ตœ์ƒ์œ„์— div๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š๊ณ  ๋ฐ˜ํ™˜ํ•ด์•ผํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์ƒ๊น€

css๊ฐ€ ๊นจ์ง„๋‹ค๊ฑฐ๋‚˜, ํ…Œ์ด๋ธ” ์š”์†Œ ์‚ฌ์ด์— div์š”์†Œ๊ฐ€ ๋“ค์–ด๊ฐ€๋ฉด error๊ฐ€ ๋ฐœ์ƒํ•˜๋Š” ๊ฒฝ์šฐ

React.Fragment๋กœ return ๊ฐ’์—์„œ ์ตœ์ƒ์œ„ tag ์—ญํ• ์„ ํ•˜๋Š” div ์—†์• ๊ธฐ

import React from "react";
export default function ReactFragment() {
  return (
    <React.Fragment>
      <h1>์•ˆ๋…•ํ•˜์„ธ์š”!</h1>
      <span>๋ฐ˜๊ฐ‘์Šต๋‹ˆ๋‹ค!</span>
    </React.Fragment>
  );
}

(react ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ์˜ ๊ธฐ๋Šฅ์ด๋ฏ€๋กœ react ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์ถ”๊ฐ€ ํ•„์š”)

 

<> </>

React.Fragment๋Š” <>๋กœ ๋Œ€์ฒด ๊ฐ€๋Šฅ !

import React from "react";
export default function ReactFragment() {
  return (
    <>
      <h1>์•ˆ๋…•ํ•˜์„ธ์š”!</h1>
      <span>๋ฐ˜๊ฐ‘์Šต๋‹ˆ๋‹ค!</span>
    </>
  );
}

 

โœ”๏ธ ํ•„์š” ์˜ˆ์‹œ)

ํ…Œ์ด๋ธ” ์š”์†Œ์•ˆ์—๋Š” div tag๊ฐ€ ๋“ค์–ด๊ฐ€์ง€ ๋ชปํ•จ

์ด๋Ÿด๋•Œ ๋ฌธ์ œ๊ฐ€ ์ƒ๊ธฐ๋Š”๋ฐ ์ด๊ฒƒ์„ react.fragment๋กœ ํ•ด๊ฒฐ ๊ฐ€๋Šฅ

import TableColumn from "./components/TableColumn";
function App() {
  return (
    <div className="App">
      <table border="1">
        <tbody>
          <tr border="1">
            <td>1</td>
            <td>2</td>
            <td>3</td>
          </tr>
          <tr>
            <TableColumn />
          </tr>
        </tbody>
      </table>
    </div>
  );
}
export default App;
// error ๋ฐœ์ƒํ•˜๋Š” ์ƒํ™ฉ
import React from "react";
export default function ReactFragment() {
  return (
    <div>
      <td>a</td>
      <td>b</td>
      <td>c</td>
    </div>
  );
}
// error ํ•ด๊ฒฐ ! 
import React from "react";
export default function ReactFragment() {
  return (
    <>
      <td>a</td>
      <td>b</td>
      <td>c</td>
    </>
  );
}

 

 

728x90

'Client > React' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

[React] useState vs useRef vs Variable  (0) 2022.09.30
[React] JSX (Javascript XML)  (1) 2022.09.26