IT/React

React 💬13

금마s 2021. 2. 2. 16:25
ReactDOM.render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {App}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>
), document.getElementById('app'))

🎈 Router 🎈

 

📌 React로 App을 라우팅 하는 법

 

 

< Step 1 - React Router 설치 >

🔧 react-router를 설치하는 간단한 방법은 밑의 코드를 cmd에 치면 된다.

>npm install react-router

 

 

< Step 2 - 컴포넌트 만들기 >

🔧 4개의 컴포넌트를 만들건데, 'App' 컴포넌트는 tab menu에 사용하고, 다른 (Home), (About), (Contact)는 route가 바뀌면 렌더링 될것이다.

 

main.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router'

class App extends React.Component {
   render() {
      return (
         <div>
            <ul>
            <li>Home</li>
            <li>About</li>
            <li>Contact</li>
            </ul>
            {this.props.children}
         </div>
      )
   }
}
export default App;

class Home extends React.Component {
   render() {
      return (
         <div>
            <h1>Home...</h1>
         </div>
      )
   }
}
export default Home;

class About extends React.Component {
   render() {
      return (
         <div>
            <h1>About...</h1>
         </div>
      )
   }
}
export default About;

class Contact extends React.Component {
   render() {
      return (
         <div>
            <h1>Contact...</h1>
         </div>
      )
   }
}
export default Contact;

 

 

< Step 3 - Router를 추가한다 >

🔧 App 요소를 렌더링하는 대신 이번에는 Router가 렌더링 될 것이다.

 

main.js

ReactDOM.render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {App}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>
), document.getElementById('app'))

 

 

💻

앱이 시작되면 이런 화면이 생긴다.

 

 

 

 

 

728x90

'IT > React' 카테고리의 다른 글

React 💬15  (0) 2021.02.04
React 💬14  (0) 2021.02.03
React 💬12  (0) 2021.02.02
React 💬11  (0) 2021.02.02
React 💬10  (0) 2021.02.02