설치
$ npm i react-helmet
이 재사용 가능한 React 컴포넌트는 문서 <head>
에 대한 모든 변경 사항을 관리합니다.
Helmet은 일반 HTML 태그를 가져와 일반 HTML 태그를 출력합니다. 정말 간단하고 React 초보자에게 친숙합니다.
import React from "react";
import { Helmet } from "react-helmet";
class Application extends React.Component {
render () {
return (
<div className="application">
<Helmet>
<meta charSet="utf-8" />
<title>My Title</title>
<link rel="canonical" href="<http://mysite.com/example>" />
</Helmet>
...
</div>
);
}
};
중첩 또는 후자의 컴포넌트는 중복 변경 사항을 재정의합니다.
<Parent>
<Helmet>
<title>My Title</title>
<meta name="description" content="Helmet application" />
</Helmet>
<Child>
<Helmet>
<title>Nested Title</title>
<meta name="description" content="Nested component" />
</Helmet>
</Child>
</Parent>
결과
<head>
<title>Nested Title</title>
<meta name="description" content="Nested component">
</head>
헤더를 변경해야 하는 경우는 언제일까? React나 Vue로 개발할 때 보통은 Mount 된 <body>
태그 안의 특정 요소에서만 작업하기 때문에 이것에 대해 신경쓸 일이 별로 없다.
그리고 이미 서버에서 헤더값을 계산해 브라우저로 내려주었기 때문에 관리할 필요도 없었다.
문서 타이틀을 변경할 때
싱글 페이지 어플리케이션(SPA)은 화면을 이동할 때마다 페이지를 요청하는 것이 아니다. 그렇기 때문에 문서의 타이틀은 맨 처음 서버에서 받은 값을 사용한다.
브라우저 단에서 라우팅이 변경되어도 이 값은 변함없이 유지된다. 화면 이동에 따라 타이틀을 변경하려면 헤더를 동적으로 변경해야만 하는데 이 때 document.title
을 사용해서 헤더를 변경한다.