programing

React.js에서 메타 태그를 업데이트하려면 어떻게 해야 합니까?

minimums 2023. 2. 27. 23:03
반응형

React.js에서 메타 태그를 업데이트하려면 어떻게 해야 합니까?

react.js에서 한 페이지 어플리케이션 작업을 하고 있었습니다만, 페이지 전환이나 브라우저의 백/포워드 메타 태그를 갱신하는 가장 좋은 방법은 무엇입니까?

이전 프로젝트에서 반응 문서 메타를 사용한 적이 있습니다.

메타 값을 정의하기만 하면 됩니다.

const meta = {
    title: 'Some Meta Title',
    description: 'I am a description, and I can create multiple tags',
    canonical: 'http://example.com/path/to/page',
    meta: {
        charset: 'utf-8',
        name: {
            keywords: 'react,meta,document,html,tags'
        }
    }

를 배치하다

<DocumentMeta {...meta} />

답례로

반응 메타 태그를 사용할 수 있습니다.제목 및 기타 메타 태그를 선언적인 방법으로 일반 jsx 형식으로 작성할 수 있으며, 이 태그는 헤드로 이동합니다(문서 상의 서버 사용 확인).

import React from 'react';
import MetaTags from 'react-meta-tags';

class Component1 extends React.Component {
  render() {
    return (
        <div class="wrapper">
          <MetaTags>
            <title>Page 1</title>
            <meta id="meta-description" name="description" content="Some description." />
            <meta id="og-title" property="og:title" content="MyApp" />
            <meta id="og-image" property="og:image" content="path/to/image.jpg" />
          </MetaTags>
          <div class="content"> Some Content </div>
        </div>
      )
  }
}

또한 고급 사용 사례가 있는 경우 react-helmet을 확인할 수도 있습니다.

거의 확실하게 다음을 사용하고 싶어합니다.

리액트 헬멧

와는 대조적으로react-meta-tags둥지를 틀 수 있다<Helmet>s 등, 애플리케이션내에서 메타데이터 태그를 정의할 수 있습니다.<title>서로 덮어쓸 필요가 있습니다.그리고 반대로react-document-metajsx(및 둥지)를 사용하여 사물을 정의할 수 있습니다.

이것은 커뮤니티가 거의 독점적으로 사용하고 있는 솔루션인 것 같습니다.- 다른 솔루션에서는 6,000개의 다운로드가 제공되고 있는 것에 비해 주간 다운로드 수는 600,000개입니다.Helmet은 플레인 HTML 태그를 사용하여 플레인 HTML 태그를 출력합니다.매우 심플하고, React 초보자 친화적입니다." 서버 사이드 렌더링을 지원합니다.

다음은 1면에서 수정한 예입니다.

<Parent>
    I'm a parent
    <Helmet>
        <title>My Title</title>
        <meta name="description" content="Helmet application" />
    </Helmet>
 
    <Child>
        I'm a 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>
<Parent>
    I'm a parent
    <Child>
        I'm a child
    </Child>
</Parent>

또한 다음과 같은 방법으로 페이지 제목과 메타 태그 설명을 제공합니다.

설명의 메타 태그를 다음과 같이 index.discription 파일에 저장합니다.

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="">
<title>Dynamic Page title here</title>

render() 메서드 아래의 .timeout 파일 또는 .timeoutx 파일에 다음과 같이 페이지 제목과 메타 설명을 입력합니다.

render()
{
document.title ="Welcome | here is your page title to display"; 
document.getElementsByTagName("META")[2].content="Your description about the page or site here to set dynamically";

return(
    <div>Page content</div>
);
}

우선 동적 데이터가 필요 없는 경우 편집만 하면 됩니다.public/index.html.

동적 데이터의 경우 React 팀은 react-helmet을 사용할 것을 권장합니다.

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>React app</title>
                <meta name="description" content="React application" />
            </Helmet>
            ...
        </div>
    );
  }
};

또는 플레이스 홀더를 사용하여 서버측에서 치환하는 방법:

<html lang="en">
  <head>
    <meta property="og:title" content="__OG_TITLE__" />
    <meta property="og:description" content="__OG_DESCRIPTION__" />
  </head>
</html>

공식 문서 React Doc - Title 및 Meta Tags따르면 React 헬멧을 사용할 수도 있습니다.

문서 조회를 사용하여 값을 업데이트할 수 있습니다.

const setTitle = title => {
    const el = document.querySelector('title');
    el.innerText = `${el.text} | ${title}`;
  };

const setDescription = desc => {
    const el = document.querySelector("meta[name='description']");
    el.setAttribute('content',desc)
  }

~하듯이create-react-app 기재된 문서:

내용을 기반으로 페이지 제목을 동적으로 업데이트해야 하는 경우 브라우저 API를 사용할 수 있습니다.React 구성 요소에서 제목을 변경하려면 타사 라이브러리인 React 헬멧을 사용할 수 있습니다.

간단한 예:

function App(){
  document.title = "Home";
  return (
   <div>...</div>
  )
}

늦은 감이 있지만 다음과 같이 간단하게 할 수 있습니다.

쓰세요.useEffect()하다

useEffect(() => {
  document.head.innerHTML+=`
  <meta name='description' content='My description value!!!'/>
  <meta name='keywords' content='My keywords!!!'/>
  `
}, []);

이것이 당신이 찾던 답인지 확실하지 않지만, 나는 당신이 다른 앱에서 링크를 미리 볼 때 당신의 리액션 앱이 보여주는 정보를 어떻게 업데이트할지 찾고 있었다.Github Github Github Github Github Github (Resact-Resign-Resign-Resign-Resign-Resign-Resign-Resign-Resign-Resign-Resign-Resign-Resign-Resign)에서 작동하지 않았습니다. 하게 된 것은 입니다.index.htmlpublic이치노머릿속 어딘가에 이것을 포함시켜 주세요.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/IMDB.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <title>IMDB</title>
    <meta property="og:audio" content="http://example.com/bond/theme.mp3" />
    <meta property="og:description" 
      content="Sean Connery found fame and fortune as the
               suave, sophisticated British agent, James Bond." />
    <meta property="og:determiner" content="the" />
    <meta property="og:locale" content="en_GB" />
    <meta property="og:locale:alternate" content="fr_FR" />
    <meta property="og:locale:alternate" content="es_ES" />
    <meta property="og:site_name" content="IMDb" />
    <meta property="og:video" content="http://example.com/bond/trailer.swf" />

https://ogp.me/의 예

 import React from 'react'
import { Helmet, HelmetProvider } from 'react-helmet-async';

const MetaData = ({ title }) => {
    return (
        <HelmetProvider>
            <Helmet>
                <title>{`${title} -  title description`}</title>
            </Helmet>
        </HelmetProvider>
    )
}

export default MetaData

언급URL : https://stackoverflow.com/questions/37734150/how-to-update-meta-tags-in-react-js

반응형