개발/React

리액트 배열을 json으로 분리하기 (react json import)

피로물든딸기 2022. 3. 1. 19:22
반응형

리액트 전체 링크

 

FAQ 같은 내용은 웹이 서비스가 되는 도중에 변경될 일이 거의 없다.

따라서 qnaList를 json으로 분리하여 파일로 관리하는 것이 좋다.

const qnaList = [
  {
    category: "category1",
    question: "what is that ? 1",
    answer: `<p>this is react. 1</p>
    <p>1 &lt; 2</p><br/>
    <span>hello!!</span>
    `,
  },
  {
    category: "category2",
    question: "what is that ? 2",
    answer: "this is react. 2",
  },
  {
    category: "category3",
    question: "what is that ? 3",
    answer: "this is react. 3",
  },
  {
    category: "category1",
    question: "what is that ? 4",
    answer: "this is react. 4",
  },
  {
    category: "category2",
    question: "what is that ? 5",
    answer: "this is react. 5",
  },
  {
    category: "category3",
    question: "what is that ? 6",
    answer: "this is react. 6",
  },
];

 

먼저 배열을 json으로 변환하자. 

아래 코드를 추가하여 console 창에서 qnaList 배열을 json으로 변경하고 출력한다.

  useEffect(() => {
    let json = JSON.stringify(qnaList);
    console.log(json);
  }, [])

 

원하는 폴더, 파일에 json 파일을 추가하고 위의 로그를 복사한다.

 

아래와 같이 json을 import하여 react에서 사용할 수 있다.

원래 qnaList에 담아도 되고, qnaList를 모두 QNA_LIST로 교체해도 된다.

import QNA_LIST from '../json/qnaList.json';
반응형