다른 js화면 불러오기

ahncheer·2023년 4월 5일
0

React

목록 보기
3/12
post-thumbnail

개인적으로 만들어보고 있습니다.
틀린부분이 있을 수 있습니다.
앞 velog와 이어지지 않습니다.

파일 구조

App.js

'Main', 'Info', 'MapShortCut', 'Support'라는 4개의 항목이 있고, 각 항목을 누르면 각 컴포넌트를 불러온다

import './App.css';
import { useState } from 'react';

/* 4개의 js 불러오기 */
import Main from './components/Main';
import Info from './components/Info';
import MapShortCut from './components/MapShortCut';
import Support from './components/Support';

/* ---- Header ---- */
function Header(props) {
  const lis = [];
  for(let i = 0; i < props.topics.length; i++){
    let t = props.topics[i];
    lis.push(<li id={t.value} key={t.value} onClick={event=>{
      event.preventDefault();
      props.onChangeMode(event.target.id);
    }}>{t.label}</li>);
  }
  return <header>
    <ul>{lis}</ul>
  </header>
}

/* ==== App ==== */
function App() {
  const [pageName, setPageName] = useState('menu1');
  const gnbList = [
    {label : 'Main', value : 'menu1'}, 
    {label : 'Info', value : 'menu2'}, 
    {label : 'MapShortcut', value : 'menu3'},
    {label : 'Support', value : 'menu4'}
  ];
  let content = null;

  if(pageName === 'menu2'){
    content = <Info></Info>;
  }else if(pageName === 'menu3'){
    content = <MapShortCut></MapShortCut>;
  }else if(pageName === 'menu4'){
    content = <Support></Support>;
  }else{
    content = <Main></Main>;
  }
  
  return (
    <div className="AppWrapper">
      <Header topics={gnbList} onChangeMode={(value)=>{
        setPageName(value);
      }}></Header>
      
        {content}
      </div>
  );
}

export default App;

App.CSS

/* common */
.layout{
  width:100%;
  max-width: 800px;

  padding: 0;
  margin: 0 auto;
}

/* header */
header{
  padding: 10px 0;
  background-color: aliceblue;
}
header ul{
  list-style: none;
  display: flex;
  gap: 100px;
  justify-content: center;
}
header ul li{
  cursor: pointer;
}

Info.js, Main.js, Support.js, MapShortCut.js

function Info(){
    return(
        <div className="wrapper">
            <p>Info입니다.</p> 
        </div>
    )
}
export default Info;

화면 확인하기

메뉴를 누를때마다 다른 js파일을 불러오는 것을 알 수 있습니다.

profile
개인 공부 기록용.

0개의 댓글