React Router를 설치하고 React에서 사용하는 방법

오늘은 React Router에 대해 배우고 우리 프로젝트에서 React Router를 구현할 것입니다.

목차


  • React 라우터란 무엇입니까?
  • 새 프로젝트 만들기
  • React Router는 어떻게 설치하나요?
  • 라우팅

  • 리액트 라우터란?



    React Router는 React 앱에서 라우팅을 생성하는 데 사용되는 라우팅 라이브러리입니다. v4 이후 React Router는 동적으로 작동하지만 이전에는 정적이었습니다.

    새 프로젝트 만들기




    npx create-react-app react-route
    cd react-route
    


    React 라우터를 설치하는 방법은 무엇입니까?



    아래 명령어를 실행하여 react-router-dom 패키지를 다운로드합니다.

    npm install react-router-dom //download and install the package
    npm start  //start development server
    


    라우팅



    서버를 시작한 후 http://localhost:3000 에서 앱을 볼 수 있습니다. 즐겨 사용하는 편집기에서 프로젝트를 열고 public/index.html로 이동합니다. 다음은 index.html의 업데이트된 코드입니다.

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta name="theme-color" content="#000000" />
        <meta
          name="description"
          content="Web site created using create-react-app"
        />
        <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
        <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
        <title>React Router Example</title>
      </head>
      <body>
        <noscript>You need to enable JavaScript to run this app.</noscript>
        <div id="root"></div>
      </body>
      <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
      <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
    </html>
    


    이제 앱에 대한 구성 요소를 만들어야 합니다. src 아래에 components라는 폴더를 만듭니다. Navbar.js, About.js, Contact.js 파일 3개 생성

    Navbar.js를 편집하고 이 코드를 붙여넣습니다.

    import React from 'react'
    import {Link} from 'react-router-dom';
    class About extends React.Component {
        render() {
            return <div
                className="d-flex flex-column flex-md-row align-items-center p-3 px-md-4 mb-3 bg-white border-bottom shadow-sm">
                <h5 className="my-0 mr-md-auto font-weight-normal"><Link className="p-2 text-dark" to="/">React Router Example</Link></h5>
                <nav className="my-2 my-md-0 mr-md-3">
                    <Link className="p-2 text-dark" to="/about">About</Link>
                    <Link className="p-2 text-dark" to="/contact">Contact</Link>
                </nav>
            </div>
        }
    }
    export default About
    


    About.js를 편집하고 이 코드를 붙여넣으세요.

    import React from 'react'
    class About extends React.Component {
        render() {
            return <div className="card">
                <div className="card-header">
                    About
                </div>
                <div className="card-body">
                   <p>
                       Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
                   </p>
                </div>
            </div>
        }
    }
    export default About
    


    Contact.js를 편집하고 이 코드를 붙여넣습니다.

    import React from 'react'
    class Contact extends React.Component {
        render() {
            return <div className="card">
                <div className="card-header">
                    Contact
                </div>
                <div className="card-body">
                    <form>
                        <div className="form-group">
                            <label >Name</label>
                            <input type="text" className="form-control"
                                   placeholder="Enter name"/>
                        </div>
    
                        <div className="form-group">
                            <label >Message</label>
                            <textarea className="form-control" id="message" name="message"
                                      placeholder="Please enter your message here..." rows="5"/>
                        </div>
    
    
                        <button type="submit" className="btn btn-primary">Submit</button>
                    </form>
                </div>
            </div>
        }
    }
    export default Contact
    


    이제 App.js를 열고 이 코드를 붙여넣습니다.

    import React from 'react'
    import {Link} from 'react-router-dom';
    class App extends React.Component {
      render() {
        return (
            <div className="card">
                <div className="card-header">
                    Homepage
                </div>
                <div className="card-body">
                    <h1>Weclome to Homepage! Content shoing from App.js</h1>
                </div>
            </div>
        )
      }
    }
    export default App
    


    이제 튜토리얼의 마지막 부분에서 index.js를 열고 코드를 업데이트합니다.

    import React from 'react'
    import ReactDOM from 'react-dom'
    import './index.css'
    import { Route, Link,Switch, BrowserRouter as Router } from 'react-router-dom'
    import App from './App';
    import NavBar from './components/Navbar'
    import Contact from './components/Contact';
    import About from './components/About';
    const routing = (
        <Router>
            <div>
    
                <NavBar/>
    
                <section className="container">
                    <Switch>
                        <Route exact path="/" component={App} />
                        <Route exact path="/about" component={About} />
                        <Route exact path="/contact" component={Contact} />
                    </Switch>
                </section>
    
            </div>
        </Router>
    )
    ReactDOM.render(routing, document.getElementById('root'))
    

    좋은 웹페이지 즐겨찾기