์๋ฆฌ๋จผํธ ๋ณํ
- cloneElement()
- isValidElement()
- React.Children
cloneElement()
React.cloneElement( element, [config], [...children] )
element๋ฅผ ๊ธฐ์ค์ผ๋ก ์๋ก์ด React ์๋ฆฌ๋จผํธ๋ฅผ ๋ณต์ฌํ๊ณ ๋ฐํ.
config๋ key์ ref, ์๋ก์ด props๋ฅผ ํฌํจํ๋ฉฐ ์๋ก์ด ์๋ฆฌ๋จผํธ์๋ ์๋ณธ ์๋ฆฌ๋จผํธ๊ฐ ๊ฐ์ก๋ props์ ์๋ก์ด props ๊ฐ ์๊ฒ ํฉ์ณ์ง๋ค.
isValidElement()
React.isValidElement(object)
๊ฐ์ฒด๊ฐ React ์๋ฆฌ๋จผํธ์ธ์ง ํ์ธํด์ true ํน์ false๋ฅผ ๋ฐํํ๋ค.
React.Children
:๋ถํฌ๋ช
์๋ฃ๊ตฌ์กฐ์ธ this.props.children์ ๋ค๋ฃจ๋ ์ ํธ๋ฆฌํฐ ํจ์๋ค์ ์ ๊ณตํ๋ค.
๋ถํฌ๋ช ์๋ฃ๊ตฌ์กฐ๋? ๊ตฌ์ฒด์ ์ธ ๋ฐ์ดํฐ๊ตฌ์กฐ๊ฐ ์ ์๋์ง ์์ ์๋ฃ๊ตฌ์กฐ๋ฅผ ์๋ฏธํ๋ค.
- React.Children.map
React.Children.map(children, function[(thisArg)])
children์ ํฌํจ๋ ์์์ ๋ํ์ฌ ํจ์๋ฅผ ํธ์ถํ์ฌ ๋ฐํํ๋ ๊ฐ๋ค์ ๋ฐฐ์ด๋ก ์์ฑํ๋ค.
children์ด null๋๋ undefined์ผ ๊ฒฝ์ฐ ์ด ๋ฉ์๋๋ ๋ฐฐ์ด์ด ์๋๋ผ null ๋๋ undefined๋ฅผ ๋ฐํํ๋ค.
children์ด Fragment์ผ ๊ฒฝ์ฐ children์ ๋จ์ผ ์์ ์ทจ๊ธ๋์ด ์ํํ์ง ์๋๋ค. (?)
- React.children.forEach
React.Children.forEach(children, function[(thisArg)])
map๊ณผ ๋น์ทํ์ง๋ง ๋ฐฐ์ด์ ๋ฐํํ์ง ์๋๋ค.
- React.Children.count
React.Children.count(children)
children์ ํฌํจ๋ ์ปดํฌ๋ํธ์ ๊ฐ์๋ฅผ ๋ฐํ
- React.Children.only
React.Children.only(children)
children์ด ๋จ ํ๋์ ์์์ ๊ฐ๋์ง ํ์ธํ๊ณ ํด๋น ์์ ์๋ฆฌ๋จผํธ๋ฅผ ๋ฐํ. ๊ทธ๋ ์ง ์์ ๊ฒฝ์ฐ ์ค๋ฅ๋ฅผ ๋ฐ์์ํจ๋ค.
React.Children.only()
๋ React.Children.map()
์ ๋ฐํ ๊ฐ์ ํ์ฉํ์ง ์๋๋ค. ๊ทธ ์ด์ ๋ map์ ๋ฐํ ๊ฐ์ React ์๋ฆฌ๋จผํธ๊ฐ ์๋๋ผ ๋ฐฐ์ด์ด๊ธฐ ๋๋ฌธ!- React.Children.toArray
React.Children.toArray(children)
๊ฐ ์์์ ๊ณ ์ ์ key๋ฅผ ํ ๋นํด์ 1์ฐจ์ ๋ฐฐ์ด๋ก ๋ณํํ์ฌ ๋ฐํํ๋ค. children์ ๋ค์ ์ ๋ ฌํ๊ฑฐ๋ ์ผ๋ถ๋ง ์๋ผ๋ด๊ณ ์ถ์ ๋ ์ ์ฉํ๋ค.
import React from "react"; export default function Sample({ children }) { console.log(children); console.log(React.Children.toArray(children)); return children; }
import Sample from "../components/sample/Sample"; export default { title: "components/Sample", component: Sample, }; const arr = [ { id: 1, fruits: "banana" }, { id: 2, fruits: "apple" }, { id: 3, fruits: "cherry" }, ]; export const Default = () => { return ( <Sample> <div fruits="mango">mango</div> {arr.map((value) => ( <li key={value.id}>{value.fruits}</li> ))} </Sample> ); };



toArray ๋ฉ์๋๋ฅผ ์ฌ์ฉํ ๊ฒฝ์ฐ ๊ฐ ์์์๊ฒ ๊ณ ์ ํ key๋ฅผ ํ ๋นํ๋ค.
์ด๋ฌํ ๊ณ ์ ํ ํค๋ children์ 1์ฐจ์ ๋ฐฐ์ด๋ก ๋ง๋ค ๋ ์ค์ฒฉ๋ ๋ฐฐ์ด์ ์๋ฏธ๋ฅผ ๋ณด์กดํ๊ธฐ ์ํ ์กฐ์น์ด๋ค.
๋ฐ๋ผ์ ํ๋์ ๋ฐฐ์ด์ธ arr๋ ๋๊ฐ์ด keyrk .1๋ก ์์ํ๋ค!
React.Fragment
์ถ๊ฐ์ ์ธ DOM์๋ฆฌ๋จผํธ๋ฅผ ์์ฑํ์ง ์๊ณ ์ต์์ ํ๊ทธ๋ก ์ฌ์ฉํ ์ ์๋ค.
import React, { Fragment } from 'react'; export default function Test (){ return( <Fragment> <h1>Hello, world!</h1> <h2>React <h2> </Fragment> ) }
๋ง์ฝ
<div>
๋ฅผ ์ฌ์ฉํ๋ ๊ฒฝ์ฐexport default function Test (){ return( <div> <h1>Hello, world!</h1> <h2>React <h2> </div> ) }

์ด๋ฐ ์์ผ๋ก DOM์ divํ๊ทธ๊ฐ ๋ํ๋๋ค. ์ด๋ฐ ๊ฒ์ Fragment๋ฅผ ์ฌ์ฉํด์ ๋ฐฉ์งํ ์ ์๋ค.
์ถ์ฝ ํํ
import React from 'react'; export default function Test (){ return( <> <h1>Hello, world!</h1> <h2>React <h2> </> ) }
์ถ์ฝ ํํ์ผ๋ก๋ ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋ค! ํ์ง๋ง ์ถ์ฝ ํํ์ key๊ฐ์ ์ค์ ํ ์ ์๋ค.