짬짬이기록하기

검색 기능 구현 본문

Web Development/React

검색 기능 구현

짬짬이기록하기 2024. 2. 7. 17:40
반응형
import { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import axios from 'axios'

	// 검색창
    const focusRef = useRef()
    const [searchClassName, setSearchClassName] = useState('search_input d-none')
    const [keyword, setKeyword] = useState('')
    
    const searchProduct = async ()=>{
        setSearchClassName('search_input d-none')
        setKeyword('')
        const resp = await axios.get('http://localhost:8000/products/keyword/' + keyword)
        if(resp.data.status === 500) window.alert(resp.data.message)
        else {
            // console.log('검색결과', resp.data.data)
            navigate('/keyword', {state: resp.data.data})
        }        
    }

    const handleEnter = e => {
        if (e.key === 'Enter') {
            e.preventDefault() //form의 input text에서 엔터키를 누르면 자동으로 Submit이 되면서 페이지가 리로드되는 현상을 막음 
            searchProduct()
        }
    }

    useEffect(()=> {
        if (searchClassName === 'search_input d-block') {
            focusRef.current.focus()
        }
    }, [searchClassName])


return (
	<div className={searchClassName} id="search_input_box">
        <div className="container">
            <form className="d-flex justify-content-between search-inner">
                <input type="text" className="form-control" id="search_input" placeholder="Search Here" 
                value={keyword} onChange={(e)=>setKeyword(e.target.value)} onKeyDown={handleEnter} ref={focusRef} style={{width:'88%'}} />
                <button type="button" className="btn form-control pt-2" onClick={searchProduct}><i className="ti-search"></i></button>
                <span className="ti-close" id="close_search" title="Close Search" onClick={()=>setSearchClassName('search_input d-none')}></span>
            </form>
        </div>
     </div>
)

 

검색결과 페이지 : navigate에서 넘긴 데이터를 useLocation을 통해 받는다. 

import { useEffect, useState } from 'react'
import { useLocation, Link } from 'react-router-dom'

const SearchKeyword = () => {
    // 검색결과 상태데이터
    const [resultList, setResultList] = useState([])

    // navigate에서 넘긴 데이타 받아오기 
    const location = useLocation()
    const result = location.state

    useEffect(()=>{
        // console.log('받은결과', result)
        setResultList(result)
    }, [location.state])

    return (
        <section className="cart_area" style={{marginTop:'140px'}}>
            <div className="container">
                <div className="col-lg-12">
                    <h3>검색결과 목록</h3>
                </div>
                <div className="cart_inner">
                    <table className="table">
                        <thead className="table-light">
                            <tr>
                                <th scope="col"><strong>product_id</strong></th>
                                <th scope="col"><strong>도서명</strong></th>
                                <th scope="col"><strong>등록이메일</strong></th>
                                <th scope="col"><strong>즉시구매가</strong></th>
                                <th scope="col"><strong>요청사항</strong></th>
                            </tr>
                        </thead>
                        <tbody>
                        {resultList[0] ? (
                            <>
                            {resultList.map((item, index) => (
                                <tr key={index}>
                                    <td>{item.product_id}</td>
                                    <td>
                                        <img src={`http://localhost:8000/static/upload/${item.picture}`} style={{width:'80px'}} />{' '}
                                        <Link to={`/products/detail/${item.product_id}`}>{item.title}</Link>
                                    </td>
                                    <td>{item.email}</td>
                                    <td>{item.master_price}</td>
                                    <td>{item.content}</td>
                                </tr>
                            ))}
                            </>
                        ) : (
                            <tr>
                                <td colSpan={5} className="text-center">검색 결과가 없습니다</td>
                            </tr>
                        )}
                        </tbody>
                    </table>
                </div>
            </div>
        </section>
    )
}

export default SearchKeyword


serside의 mysql 구문 : '%' 해줘야 함. 

"SELECT * FROM product WHERE title LIKE '%' ? '%' "
반응형

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

props.children  (0) 2024.02.08
styled-components  (0) 2024.02.08
React 강의 요점 정리  (1) 2024.02.08
pagination 구현  (0) 2024.02.07
검색창에 autoFocus 추가  (0) 2024.02.07