카테고리 없음

[React-native] 검색기능 구현3 (검색어 필터링하기)

성코 2024. 6. 21. 12:03

2024.06.20 - [분류 전체보기] - [React-native] 검색기능 구현1 (UI 구현)

2024.06.21 - [Fronted] - [React-native] 검색기능 구현2 (키보드 위 배너 잘림 현상 수정하기 - KeyboardAvoidingView)

구현과정

1. 상위컴포넌트에서 검색어 필터처리와 상태관리를 위해 작업

2. 하위컴포넌트에서는 로직을 사용하기 위해 파라미터로 함수를 전달했고

검색어가 변경되거나, 검색어를 지우면 함수를 호출하도록 연결 작업을 했다


1. 상위컴포넌트 생성자에 검색어를 담는 search와 검색결과 리스트를 담는 searchList를 추가한다

constructor(props) {
    // 생성자
    super(props);
    this.focus = React.createRef();
    this.state = {
      appState: AppState.currentState,
      basis: RNLocalize.getCountry() === 'KR' ? 'kor' : 'who',
      refreshVisible: false,
      modalVisible: true,
      isAutoRefresh: false,
      isLoaded: false,
      isError: false,
      isRefreshing: false,
      isIrOpen: false,
      isSearchOpen: false, //HeadSearchBox
      search: '', //검색어
      searchList: [], //검색 결과 리스트
    };
  }

2. searchBox 초기 데이터 설정

검색어를 입력하지 않은 상태에서는 처음 가져온 전체리스트를 보여줘야하기 때문에 상위컴포넌트에 추가했다

async componentDidUpdate(prevProps) {
    if (prevProps.deviceInfoList !== this.props.deviceInfoList) {
      this.updateSearchList();
    }
}

updateSearchList = () => {
    this.setState({ searchList: this.props.deviceInfoList}); //searchBox 초기 데이터 설정
    }

3. 검색로직 추가

검색결과가 없을 때 전체 리스트를 보여주기 위해 분기 처리 추가했다

handleSearch = (text) => {
    const filteredList = this.props.deviceInfoList.filter(device =>
      device.nickname.toUpperCase().includes(text.toUpperCase())
    );
    if (filteredList.length === 0) {
      this.setState({ search: text, searchList: this.props.deviceInfoList });
      //검색결과가 없으면 전체리스트를 보여준다
    } else {
      this.setState({ search: text, searchList: filteredList });
      //검색결과가 있으면 해당하는 리스트만 보여준다
    }
    console.log('text >>> ', text);
    console.log('filteredList >>> ', filteredList);
  };

4. X 아이콘 클릭시 입력 텍스트가 지워지고, 검색결과에 기존 deviceInfoList가 노출되도록 설정

handleDelete = () => {
    this.setState({ search: '', searchList: this.props.deviceInfoList });
    console.log('clear~~~');
  };

5. UI제어를 위해 구현 컴포넌트 HeadSearchBox에 검색어 search와 handleSearch, handleDelete를 전달한다

<HeadSearchBox
  expanded={this.state.isSearchOpen}
  search={search}
  handleSearch={this.handleSearch}
  handleDelete={this.handleDelete}
 />

 

하위컴포넌트에서는 TextInput에 onChangeText에 handleSearch를 넣어 텍스트가 변경될 때마다 상위컴포넌트의 handleSearch를 호출하도록 작업했다. 

export const HeadSearchBox = ({expanded, search, handleSearch, handleDelete}) => {

//...

return (

//...
	<View
      name="label"
      h="80%"
      justifyContent="center"
      flex={1}
      marginBottom={2}>
      <TextInput
        style={styles.input}
        placeholder={t('기기명 입력')}
        value={search}
        onChangeText={handleSearch} // 텍스트 변경시 상위컴포넌트 handleSearch 호출
      />
    </View>
    <View
      name="delete"
      h="80%"
      justifyContent="center"
      marginBottom={2}>
      <Pressable onPress={handleDelete}> // X아이콘 클릭시 상위컴포넌트 handleDelete 호출
        {({isPressed}) => (
          <Center
            w={responsiveFontSize(5)}
            h={responsiveFontSize(5)}
            borderRadius="md">
            <Octicons
              name="x-circle-fill"
              size={20}
              color={
                isPressed ? colors.BlackGrey : colors.LightBlackGrey
              }
            />
          </Center>
        )}
      </Pressable>
    </View>

 

검색기능 구현작업 완성!