본문 바로가기
my_lesson/_ReactJS

React-router - Add Router & Link

by boolean 2018. 4. 10.
728x90

ReactJS - Add Router & Link

Notice
react-router - Provides thr core routing functionality server
react-router-dom - If you are writing an applicaton that will run in the browser, you should install this.
react-router-native - If you are writing a React Native application(mobile), you should install this.
~$sudo yarn global add create-react-app
~$create-react-app cra-router
~$cd cra-router
~cra-router$ yarn add react-router-dom
~cra-router$ cd src && mkdir routes
~cra-router/src/routes$ cd routes && touch Contact.css && touch Contact.js
~cra-router/src/routes touch About.js && touch About.css
~cra-router/src/routes$ 
 ~cra-router/src/routes$ Home.js
import React from 'react';
import './Home.css';
const Home= () => {
    return (
                <div>
                    Home
                </div>
    )
}

export default Home;

~cra-router/src/routes$ About.js
import React from 'react';
import './About';

const About= () => {
    return (
                <div>
                    About
                </div>
    )
}

export default About;

~cra-router/src$mkdir components && cd components && touch Header.js && touch Header.css
~cra-router/src/components$ Header.js
import React from 'react';
import { Link } from 'react-router-dom';
import './Header.css';

const Header = () => {
    return (
        <div className="header">
            <Link to="/" className="item">홈</Link>
            <Link to="/about" className="item">소개</Link>
        </div>
    );
};

export default Header;
~cra-router/src/components$ Header.css
.header {
    background: #5c7cfa;
    display: table;
    table-layout: fixed;
    width: 100%;
}

.item {
    text-align: center;
    padding-top: 1rem;
    padding-bottom: 1rem;
    display: table-cell;
    color: white;
    text-decoration: none;
    font-size: 1.1rem;
}

.item:hover {
    background: #748ffc;
}

.item:active {
    background: white;
    color: #5c7cfa;
}

~cra-router/src$App.js
하나의  <Router> 안에는 하나의 child만 있어야한다.
A <Router> may have only one child element.
import React  from 'react';
import { BrowserRouter as Router, Route} from 'react-router-dom';

import Home from './routes/Home';
import About from './routes/About';

import Header from './components/Header';

const App = () => {
    return (
            <Router>
                <div>
   <Header />
                    <Route exact path='/' component={Home} />
                    <Route path='/about' component={About} />
                </div>
            </Router>
    )
}

export default App;



댓글