PROGRAMING/FULL STACK

[Front End] URL parameters with React Router

donghunl 2024. 3. 9. 06:46
반응형

URL 매개변수 이용

 

Article page에서 각 컨텐츠를 보여주기 위해 URL변수를 이용해서 Page가 로드되도록 설정합니다.

그래서 일단 컨텐츠 내용를 담은 page를 src폴더->pages폴더 밑에 article-content.js 파일을 추가합니다.

 

article-content.js

const articles = [
    {
        name: 'learn-react',
        title: 'The Fastest Way to Learn React',
        content: [
            `Welcome! Today we're going to be talking about the fastest way to
            learn React. We'll be discussing some topics such as install Node.js and React.`,
            `어서 오세요! 오늘은 리액트를 배우는 가장 빠른 방법에 대해 이야기 할 것입니다. Node.js 설치 및 리액트와 같은 몇 가지 주제에 대해 논의 할 것입니다.`,
            `¡Bienvenidos! Hoy vamos a hablar de la forma más rápida de aprender a reaccionar. Estaremos discutiendo algunos temas como instalar Node.js y reaccionar.`,
            `Bienvenue ! Aujourd'hui, nous allons parler du moyen le plus rapide d'apprendre React. Nous discuterons de certains sujets comme l'installation de Node.js et React`,
            `いらっしゃいませ! 今日は、Reactを学ぶ最も早い方法についてお話しします。 Node.jsやReactのインストールなど、いくつかのトピックについて説明します。`,
        ]
    }, {
        name: 'learn-node',
        title: 'How to Build a Node Server in 10 Minutes',
        content: [
            `In this article, we're going to be talking about a very quick way
            to set up a Node.js server. We'll be discussing some topics such as what you want to know.`,
            `이 기사에서는 Node.js 서버를 설정하는 매우 빠른 방법에 대해 이야기 할 것입니다. 알고 싶은 것과 같은 몇 가지 주제에 대해 논의 할 것입니다.`,
            `En este artículo, vamos a hablar de una manera muy rápida de configurar un servidor Node.js. Discutiremos algunos temas como lo que usted quiere saber.`,
            `Dans cet article, nous allons parler d'un moyen très rapide d'installer un serveur Node.js. Nous discuterons de sujets tels que ce que vous voulez savoir.`,
            `この記事では、Node.js サーバを簡単にセットアップする方法について説明します。 皆さんが知りたいことなど、いくつかのテーマについてお話しします。`,
        ]
    }, {
        name: 'mongodb',
        title: 'Learn MongoDB',
        content: [
            `MongoDB Atlas' document model enables developers to store data as JSON-like objects that resemble objects in application code. With MongoDB Atlas, use the tools and languages that you prefer. Manage your clusters with MongoDB CLI for Atlas, or IaC tools like Terraform or Cloudformation.`,
            `MongoDB Atlas의 문서 모델을 사용하면 개발자는 애플리케이션 코드의 객체와 유사한 JSON과 같은 객체로 데이터를 저장할 수 있습니다. MongoDB Atlas에서 원하는 도구와 언어를 사용합니다. Terraform이나 Cloudformation과 같은 IaC 도구 또는 MongoDB CLI for Atlas로 클러스터를 관리할 수 있습니다.`,
            `El modelo de documentos de MongoDB Atlas permite a los desarrolladores almacenar datos como objetos similares a JSON que se asemejan a objetos en código de aplicación. Con MongoDB Atlas, utilice las herramientas y idiomas que prefieras. Administre sus grupos con MongoDB CLI para Atlas, o herramientas IaC como Terraform o Cloudformation.`,
            `Le modèle de document de MongoDB Atlas permet aux développeurs de stocker des données en tant qu'objets similaires à JSON qui ressemblent à des objets dans le code d'application. Avec MongoDB Atlas, utilisez les outils et les langues que vous préférez. Gérez vos clusters avec MongoDB CLI pour Atlas, ou des outils de l'IAC comme Terraform ou Cloudformation.`,
            `MongoDB Atlasのドキュメントモデルにより、開発者はアプリケーションコード内のオブジェクトに似たJSONのようなオブジェクトとしてデータを保存することができます。 MongoDB Atlas では、好きなツールと言語を使用します。 MongoDB CLI for AtlasまたはTerraformやCloudformationなどのIaCツールを使用してクラスタを管理できます。`,
        ]
    },
];

export default articles;

 

여기서 URL 변수로 articleId을 이용하는데 article-content안의 name 항목과 매칭을 시키고 그 변수에 맞게 내용를 불러오도록 다음과 같이 ArticlePage.js파일을 변경합니다.

ArticlePage.js

import { useParams } from 'react-router-dom';
import articles from './article-content';

const ArticlePage = () => {
    const { articleId } = useParams();
    const article = articles.find(article => article.name === articleId);

    return (
        <>
            <h1>{article.title}</h1>
            {article.content.map(paragraph => (
                <p >{paragraph}</p>
            ))}
        </>
    );
}

export default ArticlePage;

 

결과 화면은 다음과 같습니다.

반응형