이번 SearchBar 구현은 총 3가지 형식으로 구성했다.
1) <TextInput> 태그형 ( 링크 : https://radpro.tistory.com/58 )
2) FlatList에 붙는 Header형 ( 링크 : https://radpro.tistory.com/59 )
3) 공식문서의 Search바 응용형 ( 링크 : https://radpro.tistory.com/60 )
본인 취향에 맞게 사용하면 되나, 개인적으로 <TextInput>형이 연동과 렌더링에 가장 용이하다고 판단한다.
------------------------------------------------------------------------------------------------
1. 설치파일
ㄱ. Flatlist를 하나 만들어준다.
ㄴ. lodash.filter 를 설치해주자
yarn add lodash.filter
2. 사용방법
ㄱ. import 단계
1) react-native에서 TextInput도 받아오자.
2) Flatlist에 lodash.filter를 import해주자
import { ..., TextInput } from 'react-native';
import filter from 'lodash.filter';
ㄴ. 두 가지 상태변수(useState)를 선언
1) query를 품은 useState : 글자를 입력하면, 검색을 위해 데이테 입력을 추적하는 상태변수
기본값은 빈 문자열이다.
2) fullData를 품은 useState : 데이터를 필터링할 때 사용할 API데이터를 저장할 변수
const [query, setQuery] = useState('');
const [fullData, setFullData] = useState([]);
ㄷ. 검색창 UI 구현단계
1) <Flatlist> 태그 안에 props로 헤더UI를 넣어주자
<FlatList
ListHeaderComponent={renderHeader}
...
/>
2) renderHeader로 설정한 값에 대한 함수를 선언해주자
즉, 선언한 헤더에 모양과 글자입력기능을 넣어주는 부분이다.
export default function App() {
...
function renderHeader() {
return (
<View
style={{
backgroundColor: '#fff',
padding: 10,
marginVertical: 10,
borderRadius: 20
}}
>
<TextInput
autoCapitalize="none"
autoCorrect={false}
clearButtonMode="always"
onChangeText={queryText => handleSearch(queryText)}
placeholder="Search"
style={{ backgroundColor: '#fff', paddingHorizontal: 20 }}
/>
</View>
);
}
ㄹ. API에 검색할 수 있도록 Query를 연동해주자
1) 방금 전 코드에서, TextInput에대한 value값을 넣어준다. value = { query } 부분
여기서 {query}는 상단에 useState로 선언한 setSearch로 업데이트되는 값을 받는 getter변수다.
...
<TextInput
autoCapitalize="none"
autoCorrect={false}
clearButtonMode="always"
value={query}
onChangeText={queryText => handleSearch(queryText)}
placeholder="Search"
style={{ backgroundColor: '#fff', paddingHorizontal: 20 }}
/>
...
2) 검색기능을 위해 선언한 Query함수를 복붙해주자.
앞서 <TextInput>에서 onChangeText를 통해 사용할 함수로 SearchForQuery로 지정했다.
SearchForQuery라는 함수를 선언해주자. 이름 그대로, 검색을 하기 위한 Query기능을 만들어줄것이다.
- 검색창에 넣을 타입은 text이다.
- text.toLowerCase( ); : 쿼리는 소문자가 기본이라는 얘기다.
- filteredData = filter(fullData, user => { return contain(user, formattedQuery); }
: filertedData라는 함수를 선언해 줄 것이다. filter는 아까 import해온 lodash.filter다.
필터링할 데이터는 fullData라는 놈과 user라는 녀석이며, 반환될 값은 user와 formattedQuery를 포함한 값이다.
formattedQuery는 직전에 소문자 검색이라 선언해둔 것의 치환값이다.
- setState는 Flatlist만들때, 데이터베이스로부터 JSON데이터를 받을 setter변수로 선언한 녀석이다.
그래서 방금 만든 데이터 변수를 넣어준다.
- setQuery는 직전 단계에서 선언한 useState변수다. 글자입력시 데이터 추적해주는 용도라 text를 넣는다.
const SearchForQuery = text => {
const formattedQuery = text.toLowerCase();
const filteredData = filter(fullData, user => {
return contains(user, formattedQuery);
});
setState(filteredData);
setQuery(text);
};
3) 검색 조건을 넣어주자.
첫 줄의 { 여기 }에 검색할 키값을 넣어준다. (내 JSON 데이터상의)
- title과 description을 props로 넣어줬다.
- 처음이나 마지막에 타이틀을 포함하라고 설정해놨다.
- description을 포함하라고 설정해놨다.
- ll : or 이란 뜻이다.
- 만약 상단의 조건이 있다면 true로 반환하고, 없으면 false란 소리다.
const contains = ({ title, description }, query) => {
const { first, last } = title;
if (first.includes(query) || last.includes(query) || description.includes(query)) {
return true;
}
return false;
};
'React-native > 정리' 카테고리의 다른 글
| Loading화면 구현 (2) (0) | 2022.05.25 |
|---|---|
| Flatlist + SearchBar (3편 공식문서 SearchBar형) (0) | 2022.05.25 |
| Flatlist + SearchBar (1편 <TextInput> 태그형) (0) | 2022.05.25 |
| fetch이해하기 (네트워킹) (0) | 2022.05.24 |
| FlatList + Iframe 연동 (0) | 2022.05.23 |