SearchButton.jsx 2.19 KB
import React, {useRef, useState} from "react";
import styled from "styled-components";

const SearchButtonWrapper = styled.div`
  display: flex;
  flex-direction: row;
  justify-content: space-between;
`;

const SearchInput = styled.input`
  width: 55%;
`;

const ApplyButton = styled.div`
  width: 17%;
  background-color: #e7e7e7;
  border-radius: 4px;
  color: #565656;
  text-align: center;

  display: flex;
  justify-content: center;
  align-items: center;

  &:hover {
  background-color: #565656;
  color: white;
  cursor: pointer;
`;

const SelectBox = styled.select`
  width: 22%;
  color: #333333;
  border-color: #E3E3E3;
  border-radius: 4px;
`;

const searchTypeKR = {
  phone_number: '전화번호',
  email: '이메일',
  user_id: '사용자ID'
};

const SearchButton = (props) => {
  const selectEl = useRef(null);
  const inputEl = useRef(null);
  const {setUserId} = props;
  const [searchType, setSearchType] = useState('phone_number');

  const searchUserData = (e) => {
    e.preventDefault();
    const searchText = inputEl.current.value;

    if(searchType === 'user_id') {
      fetch(`http://1.201.143.67:5901/user/${searchType}`)
        .then(r => r.json())
        .then(d => {
          if(d.success) setUserId(searchType);
          else setUserId('-1'); // 검색결과 X
        })
    } else {
      fetch(`http://1.201.143.67:5901/user/${searchType}/${searchText}`)
        .then(r => r.json())
        .then(d => {
          if(d.success) setUserId(d.data[0].user_id);
          else setUserId('-1'); // 검색결과 X
        })
    }
  };

  const onChangeSearchOption = (e) => {
    setSearchType(e.target.value)
  };

  return (
    <SearchButtonWrapper>
      <SelectBox ref={selectEl} onChange={(e) => onChangeSearchOption(e)}>
        <option value="phone_number">전화번호</option>
        <option value="email">이메일</option>
        <option value="user_id">사용자ID</option>
      </SelectBox>
      <SearchInput type="text" ref={inputEl} className="form-control" placeholder={`${searchTypeKR[searchType]}로 검색하기`}/>
      <ApplyButton onClick={(e) => searchUserData(e)}><span>검색</span></ApplyButton>
    </SearchButtonWrapper>
  );
};

export default SearchButton;