4장 서버 사이드 렌더링(2)

4.2 서버 사이드 렌더링을 위한 리액트 API 살펴보기

기본적으로 리액트는 프런트엔드 라이브러리로 브라우저 자바스크립트 환경에서 렌더링할 수 있는 방법을 제공하지만 이와 동시에 리액트 애플리케이션을 서버에서 렌더링할 수 있는 API도 제공한다. 이 API는 당연히 브라우저의 window 환경이 아닌 Node.js와 같은 서버 환경에서만 실행할 수 있으며 window 환경에서 실행 시 에러가 발생할 수 있다.

4.2.1 renderToString
function ChildrenComponent({ fruits }: { fruits: Array<string> }) {
    useEffect(() => {
        console.log(fruits)
    }, [fruits])

    function handleClick() {
        console. log('hello')
    }
    return (
        <ul>
        {fruits.map((fruit) => (
            <li key={fruit} onClick={handleClick}>
        {fruit}
        </li>
        ))}
        </ul>
    )
}
function SampleComponent() {
    return (
        <>
        <div>hello</div>
        <ChildrenComponent fruits={['apple', 'banana', 'peach']} />
        </>
    )
}
const result = ReactDOMServer.renderToString(
    React.createElement('div', { id: 'root' }, SampleComponent />),
)
<div id="root" data-reactroot="">
    <div>hello</div>
    <ul>
        <li>apple</li>
        <li>banana</li>
        <li>peach</li>
    </ul>
</div>

끝!