TIL - React helmet

박지민·2022년 7월 18일
0

TIL

목록 보기
15/25
post-thumbnail

1. 리액트에서 각 페이지 컨텐츠에 맞는 미리보기를 띄워보자


기존에 MPA(Multi Page Application)로 웹 개발을 했을 때에는 각각에 페이지의 HTML 문서마다 Meta tag의 내용을 변경해 각 페이지 컨텐츠에 맞는 미리보기를 보여줄 수 있었다. 하지만 리액트는 SPA(Single Page Application)이기 때문에 리액트로 만든 웹페이지의 링크를 공유 했을 때나 포털사이트에서 리액트로 만들어진 사이트를 읽어 올 때 단 하나의 HTML 문서를 읽게 되며 각각의 미리보기를 제공하는 것이 불가능하다는 단점이 존재했다.

이러한 단점을 극복하기 위해 나온것이 React-helmet 라이브러리이다. React-helmet 라이브러리를 이용하면 각각의 페이지마다 Meta tag를 설정해 주는 것이 가능하다.

2. React-helmet 라이브러리 사용해보기


  1. react-helmet을 설치한다.
    $ yarn add react-helmet-async

  2. index.js 파일에서 HelmetProvider 컴포넌트로 App 컨포넌트를 감싼다.

()
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <HelmetProvider>
    <App />
  </HelmetProvider>
);
()
  1. Meta tag를 변경해 주고 싶은 컨포넌트에서 다음과 같이 작성해 Meta tag를 변경해 준다.
import React from "react";
import {Helmet} from "react-helmet";
const One = (props) => {
    return (
      <div>
        <Helmet>
          <title>page one</title>
          <meta property="og:title" content="page one" />
          <meta property="og:description" content="hi there :) page one" />
          <meta property="og:image" content="%PUBLIC_URL%/logo192.png" />
        </Helmet>
()

3. 참조


스파르타 코딩클럽 리액트 심화반 5주차 강의자료
https://velog.io/@miyoni/noSSRyesSEO

profile
프론트엔드 개발자

0개의 댓글