TIL/JavaScript

TIL 34: [React] ๋ฐ์ดํ„ฐ ํ๋ฆ„์˜ ์ดํ•ด์™€ ๋น„๋™๊ธฐ ์š”์ฒญ ์ฒ˜๋ฆฌ

Deviloper๐Ÿ˜ˆ 2021. 9. 7. 21:11

์˜ค๋Š˜์€ ์–ด์ œ์— ์ด์–ด์„œ StateAirlines๋ฅผ ๋งˆ์ € ํ–ˆ์Šต๋‹ˆ๋‹ค. ์ƒˆ๋กœ ๋ฐฐ์šด ๋‚ด์šฉ์€ ์—†์–ด ์ฒ˜์Œ ํ’€์—ˆ์„ ๋•Œ ํ—ค๋งธ๋˜ ์œ„์ฃผ๋กœ ์ •๋ฆฌํ•ด๋ณด๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค!

 

Lifting State Up

 

๋ถ€๋ชจ์ปดํฌ๋„ŒํŠธ์— ์•„๋ž˜์™€ ๊ฐ™์ด search ํ•จ์ˆ˜๋ฅผ onSearch๋ฅผ ํ†ตํ•ด ์ „๋‹ฌํ•ด์ฃผ๋ฉด,

<Search onSearch={search} />

์ž์‹ ์ปดํฌ๋„ŒํŠธ์—์„œ ํ•จ์ˆ˜(Search)๊ฐ€ ์‹คํ–‰๋˜๋ฉด onSearch์— ์˜ํ•ด ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋ณ€๊ฒฝ๋ฉ๋‹ˆ๋‹ค.

import { useState } from 'react'

function Search({onSearch}) { //onSearch ๋„ฃ์–ด์ฃผ๊ธฐ, Main์—์„œ๋„ <Search onSearch={search} />ํ•ด์ฃผ๊ธฐ
  const [textDestination, setTextDestination] = useState('')

  const handleChange = (e) => {
    setTextDestination(e.target.value.toUpperCase())
  }

  const handleKeyPress = (e) => {
    if (e.type === 'keypress' && e.code === 'Enter') {
      handleSearchClick()
    }
  }

  const handleSearchClick = () => {
    const departure = 'ICN' //๋งค๊ฐœ๋ณ€์ˆ˜ ์—†์œผ๋‹ˆ departure destination ๋”ฐ๋กœ ์„ค์ •ํ•ด์ฃผ๊ธฐ
    const destination = textDestination === '' ? null : textDestination
    onSearch({departure,destination})
  }

  return <fieldset>
    <input id="input-destination" type="text" value={textDestination} onChange={handleChange} placeholder="CJU, BKK, PUS ์ค‘ ํ•˜๋‚˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”" onKeyPress={handleKeyPress} />
    <button id="search-btn" onClick={handleSearchClick}>๊ฒ€์ƒ‰</button>
  </fieldset>
}

export default Search