검색창 만들기

miin·2021년 10월 16일
0
post-thumbnail

내용

  • 메인페이지에 있는 검색창 만들기
  • 클릭시 검색창에 search 텍스트 없애기
  • 검색후 필터링된 페이지로 이동

결과

코드

import React, { Component } from 'react';
import { withRouter } from 'react-router';

class Input extends Component {
  constructor() {
    super();
    this.state = {
      placeholder: 'SEARCH',
      products: [],
      keyword: '',
    };
  }

  getData = () => {
    const { keyword } = this.state;
    const { history } = this.props;
    fetch(`http://10.58.0.90:8000/products?keyword=${keyword}`)
      .then(res => res.json())
      .then(res => {
        this.setState({ products: res.result });
        history.push(`/products?keyword=${keyword}`);
      });
  };

  handleChange = e => {
    this.setState({
      keyword: e.target.value,
    });
  };

  handleInputCheck = e => {
    e.preventDefault();
    const { value } = e.target[0];
    value ? this.getData() : alert('검색어를 입력해주세요.');
  };

  handleInput = () => {
    this.setState({
      placeholder: '',
    });
  };

  render() {
    return (
      <div className="searchBox">
        <form onSubmit={this.handleInputCheck}>
          <input
            className="search"
            type="search"
            placeholder="SEARCH"
            onFocus={this.handleInput}
            onChange={this.handleChange}
          />
        </form>
      </div>
    );
  }
}

export default withRouter(Input);

설명

placeholder 커서시 없애기

.scss
input:focus::placeholder{
  color:transparent; //투명으로 바꿔주기
}

.js
constructor(){
  super();
  this.state = {
    placeholder: 'SEARCH',
  };
}

handleInput = () => {
	this.setState({
      placeholder: '',
    });
}

render(){
  return(
    <input
    className ="search"
    type="search"
    placeholder="SEARCH"
    onFocus={this.handleInput}
	/>
}

*color: transparent -> 부모와 같은 색으로 따라가기

검색 값 저장하기

constructor(){
  super();
  this.state = {
    //검색된 값을 담을 요소
    keyword: '',
  }

 //keyword에 검색어(값)를 할당하는 함수 
handleChange = e => {
  this.setState({
    keyword: e.target.value,
  });
}

render(){
  return(
      <div className="searchBox">
          <input
            className="search"
            type="search"
            placeholder="SEARCH"
    //onChange 이벤트가 실행되면 handleChange 함수를 호출
            onChange={this.handleChange}
          />
      </div>
	);
}

검색된 데이터 불러오기

//router에 연결이 안되어 있지만 사용할때 withRouter
import { withRouter } from 'react-router';

  constructor() {
    super();
    this.state = {
  // 받은 데이터를 저장할 빈 배열
      products: [],
      keyword: '',
    };
  }

//데이터 불러오는 fetch 함수
getData = () => {
  const { keyword } = this.state;
  const { history } = this.props;
  //백엔드서버: 10.58.0.90:8000/products?keyword=
  //검색어가 저장된 요소 &{keyword}
  fetch(`http://10.58.0.90:8000/products?keyword=${keyword}`)
      .then(res => res.json())
      .then(res => {
    //products에 백에서 받아온 result(백 데이터의 객체명)를 할당하기
        this.setState({ products: res.result });
    //this.props.history.push로 해당 검색어가 필더링된 페이지로 이동
        history.push(`/products?keyword=${keyword}`);
      });
}

//값을 받아오는 함수
handleInputCheck = e => {
  //페이지의 디폴트값을 제어해줌 (새로고침 x, 새로고침을 하게되면 값이 사라짐)
 e.preventDefault();
  //구조분해할당
 const { value } = e.target; 
 // 값이 있으면 데이터를 불러오는 함수를 호출하고, 그렇지 않으면 알림띄우기
  value ? getData() : alert('검색어를 입력하세요.');
}

render(){
  return(
     <div className="searchBox">
	// onSubmit은 엔터가 default값 이다
    //검색어를 입력하고 엔터를 치면 handleInputCheck 함수를 호출
        <form onSubmit={this.handleInputCheck}>
          <input
            className="search"
            type="search"
            placeholder="SEARCH"
          />
        </form>
      </div>
    );
  }
  
  export default withRouter(Input);

0개의 댓글