코리아 IT아카데미/react.js

6일차 | react_Route

Sharon kim 2022. 3. 16. 19:24

 

App.js

import React from 'react';
import { Route, Link } from 'react-router-dom';
import Home from './home';
import About from './about';
import Profiles from './profiles';

 const App = () => {
  return (
    <>
    <ul>
      <li><Link to='/'>홈</Link></li>
      <li><Link to='/about'>소개</Link></li>
      <li><Link to='/profiles'>유저리스트</Link></li>
    </ul>
    < hr/>
    <div>
       <Route path="/" exact={true} component={Home}/>
       <Route path="/about" component={About}/>
       <Route path="/profiles" component={Profiles}/>
    </div>
    </>
  );
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import './index.css';
import App from './App';


ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
);

 

home.jsx

import React from "react";


const Home = () => {
    return(
        <div>
            <h1>홈</h1>
            <p>길동의 웹사이트에 오신 것을 환영합니다</p>
        </div>
    )
}

export default Home;

about.jsx

import React from "react";


const About = () => {
    return(
        <div>
            <h1>소개</h1>
            <p>리액트 라우터를 공부하고 있어요</p>
        </div>
    )
}

export default About;

profile.jsx

import React from "react";

const profileData = {
    apple: {
        name: '김사과',
        description: '학생, 착해요'
    },
    banana: {
        name: '반하나',
        description: '회사원, 잘자요'
    }
};


const Profile = ({ match }) => {
    //파라미터를 받아올 땐 match 안에 들어있는 params 값을 참조합니다.
    const { username } = match.params;
    const profile = profileData[username];

    if(!profile){
        return <div>존재하지 않는 프로필입니다</div>
    }
    return (
        <div>
            <h2>
                {username}({profile.name})
            </h2>
            <p>{profile.description}</p>
        </div>
    );
};

export default Profile;

profiles.jsx

import React from "react";
import { Link, Route } from 'react-router-dom';
import Profile from './profile';
//yarn add react-router-dom@5

const Profiles = () => {
    return(
        <div>
            <h1>유저목록</h1>
            <ul>
              <li>
                <Link to ='/profiles/apple'>apple</Link>   
              </li>    
              <li> 
                 <Link to ='/profiles/banana'>banana</Link> 
              </li>
            </ul>

            {/* <Route path="/apple" component={Apple}/>
            <Route path="/banana" component={Banana}/> */}
            <Route path='/profiles' exact render={() => <div>유저를 선택하세요</div>}></Route>
            <Route path="/profiles/:username" component={Profile}/>
        </div>
    )
}

export default Profiles;