React Query String

React/React 2022. 6. 8. 00:05
728x90

http://localhost:3000/about?name=react&id=123 와 같은 URL 입력값에서 Query String을 추출하는 함수 예제이다.

React 강의를 듣고 그대로 타이핑을 하는데 동작이 안된다. 오래된 버전이라 그런가???

구글링을 해보고 그대로 실행해보는데도 역시 안되는 것들이 있다.

react-router-dom v6 에 맞게 구현해야 동작된다.

import React, {useState} from 'react';
import { useLocation } from 'react-router';
import qs from "query-string";  // npm install query-string
 
 
const About = () => {
    // In React Hooks:
    const searchParams = useLocation().search;
    console.log(searchParams);
    const query = qs.parse(searchParams);
    console.log(query);
 
    const name = new URLSearchParams(searchParams).get('name');
    const id = new URLSearchParams(searchParams).get('id');
    console.log({ name, id });
 
    return (
        <div>
            <h2>About 페이지입니다.</h2>
            {query.name && <p>name 은 {query.name} 입니다.</p>}
        </div>
    );
};
 
// https://everttimberg.io/blog/custom-react-hook-query-state/ 참고하자.
 
export default About;

 

비구조화 할당 문법을 통해 props 내부 값 추출하기

import {Route, Routes, useParams} from "react-router-dom";
import Home from "./pages/Home";
import Profile from "./pages/Profile";
import About from "./pages/About";
 
function App() {
    const { id } = useParams();
    return (
        <Routes>
            <Route path="/" element={<Home />}/>
            <Route path="/profile" element={<Profile/>}/>
            <Route path="/profile/:id" element={<Profile/>}/>
            <Route path="/about" element={<About name={"React"/>}/>
        </Routes>
    );
}
 
export default App;

 

props는 컴포넌트가 사용되는 과정에서 부모 컴포넌트가 설정하는 값이며,

컴포넌트 자신은 해당 props를 읽기 전용으로만 사용할 수 있다.

{props.name} 대신에 {name} 으로 내부 값을 바로 추출하는 방법 : const { name } = props;

import React, {useState} from 'react';
import { useLocation } from 'react-router';
import qs from "query-string";  // npm install query-string
 
 
const About = props => {
    // In React Hooks:
    const searchParams = useLocation().search;
    console.log(searchParams);
    const query = qs.parse(searchParams);
    console.log(query);
 
    //const name = new URLSearchParams(searchParams).get('name');
    //const id = new URLSearchParams(searchParams).get('id');
    //console.log({ name, id });
 
    const { name } = props; // 비구조화 할당 문법
 
    return (
        <div>
            <h2>{name} About 페이지입니다.</h2>
            {query.name && <p>name 은 {query.name} 입니다.</p>}
        </div>
    );
};
 
 
export default About;

리액트에는 두가지 종류의 state가 있다.

하나는 클래스형 컴포넌트가 지니고 있는 state 이고,

다른 하나는 함수 컴포넌트에서 useState라는 함수를 통해 사용하는 state이다.

 

 

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

React-bootstrap Header.js 테스트  (0) 2022.08.21
React CORS error 해결 방법  (0) 2022.08.20
React Router v6  (0) 2022.06.07
React useState  (0) 2022.06.04
React 값 전달(부모 → 자식, 자식 → 부모)  (0) 2022.06.03
블로그 이미지

Link2Me

,