22-11-16-리액트(5)

YJ·2022년 11월 16일
0
post-thumbnail

리액트 라우터

  • 기본 모듈 명령어
npx create-react-app my-app --template basic-react

위의 명령어는 3기 동기분께서 기본 모듈을 만들어 주셨습니다. 👍

  • 라우터 설정
npm install react-router-dom

Component props 전달하기

import {BrowserRouter, Routes, Route} from 'react-router-dom';

function App() {
	return (
    	<BrowserRouter>
      		{/* 라우트를 감싸주기 */}
      		<Routes>
      			<Route path='/' element={<Index/>}/>
      			<Route path='/one' element={<One name = 'lee'/>}/>
      		</Routes>
      	</BrowserRouter>
    )
}

function Index() {
	return (<h1>hello Index</h1>)
}
function One({name}) {
	return (<h1>{name}hello One</h1>)
}

export default App;

주소만 바꿀 뿐 페이지 새로 고침은 안함

<Link to='/about'>About</Link>

to 속성에 접근할 경로가 들어간다.

  • a 태그는 클릭시 페이지 새로 불러오므로 페이지 새로 고침 현상이 나타난다.
  • link 태그는 브라우저 주소만 변경하므로 페이지 새로 고침 현상 없이 dom만 조작해서 페이지를 보여준다.
import {BrowserRouter, Routes, Route, Link} from 'react-router-dom';

function App() {
	return (
    	<BrowserRouter>
      		<Link to='/'>home</Link>
      		<Link to='/one'>one</Link>
      		{/* 라우트를 감싸주기 */}
      		<Routes>
      			<Route path='/' element={<Index/>}/>
      			<Route path='/one' element={<One name = 'lee'/>}/>
      		</Routes>
      	</BrowserRouter>
    )
}

function Index() {
	return (<h1>hello Index</h1>)
}
function One({name}) {
	return (<h1>{name}hello One</h1>)
}

export default App;

파라미터 설정

import {BrowserRouter, Routes, Route, Link, useLocation} from 'react-router-dom';

function App() {
	return (
    	<BrowserRouter>
      		<Link to='/'>home</Link>
      		<Link to='/one'>one</Link>
      		{/* 라우트를 감싸주기 */}
      		<Routes>
      			<Route path='/' element={<Index/>}/>
      			<Route path='/one' element={<One name = 'lee'/>}/>
                {/* blog/:id로 추가 */}
        		{/* blog/1 등 입력 */}
       			<Route path="/blog/:id" element={<Blog />}/>
      		</Routes>
      	</BrowserRouter>
    )
}

function Index() {
	return (<h1>hello Index</h1>)
}
function One({name}) {
	return (<h1>{name}hello One</h1>)
}
function Blog(){
  const location = useLocation();
  // pathname에 주소가 나옵니다. pathname : "/blog/1"
  console.log(location);
  // 뒷자리에 따라서 다르게 표현해주고 싶은 경우
 
  // 파라미터 사용 예1
  console.log(location.pathname.split('/')[2]);
  const urlSlicingValue = location.pathname.split('/')[2];
  
  // 파라미터 사용 예2
  const {id} = useParams();
  const imgUrl = `http://test.api.weniv.co.kr/asset/img/${urlSlicingValue}/thumbnailImg.jpg`;
  return (
    <>
      <h1>hello Blog</h1>
      <img src={imgUrl} alt="" />
    </>
  )
}

export default App;
profile
함께 배워나가고 싶습니다!

0개의 댓글