생각은 길게 코딩은 짧게

[React-Native] RadioButton 구현 ( 최신순 / 가나다순 ) 본문

React Native

[React-Native] RadioButton 구현 ( 최신순 / 가나다순 )

sayhee 2023. 1. 4. 23:58
728x90

RadioButton으로 최신순, 가나다순으로 정렬될 수 있도록 sorting을 구현해보았습니다


import RadioButton Icon 

- MaterialIcon을 사용하였습니다

import IconRadio from 'react-native-vector-icons/MaterialIcons';

 

 

ComponentDidMount ( 최신순 )

componentDidMount() {
    this.setState({indicator : true}); //ActivityIndicator
    this.callGetGoodsAPI().then((response) => {
        this.Contents = response;
        this.setState({ goodsContent: response }); //최신순
        this.setState({indicator : false});
    });
    BackHandler.addEventListener("hardwareBackPress", this.backPressed); //뒤로가기 이벤트
}

처음 서버에서 가져오는 List의 default 값은 최신순입니다

 

정렬 된 List를 가져오기 위한 서버 호출

sortDidMount = (value) => {
    this.setState({ indicator: true });
    this.callGetGoodsAPI().then((response) => {
        this.Contents = response;
        this.setState({ goodsContent: value });
        this.setState({ indicator: false });
    });
}

 

sorting을 위한 함수 구현

dateSort = () => { //최신순
    this.setState({recentRadioButtonChecked: true, abcRadioButtonChecked: false });
    this.setState({ goodsContent: this.goodsContent });
    this.componentDidMount();
}

abcSort=()=> { //가나다순
    this.setState({recentRadioButtonChecked: false, abcRadioButtonChecked: true });
    this.state.goodsContent.sort((a, b) => { //가나다순 sorting을 위한 구문
        return a.name.localeCompare(b.name);
    })
    this.setState({ goodsContent: this.goodsContent });
    this.sortDidMount(this.state.goodsContent); //value 값은 가나다순 정렬된 goodsContent

}

dateSort 함수는 최신순이므로 default 값인 componentDidMount를 호출해주었습니다.

 

View

<View style={styles.row}>
    <View style={{ flexDirection: 'row' }}>
        <TouchableOpacity style={{ flexDirection: 'row' }} activeOpacity={0.8} onPress={this.dateSort}>
            <IconRadio name={this.state.recentRadioButtonChecked ? "check-circle" : "panorama-fish-eye"} size={20} color={'lightgrey'} style={{ paddingTop: 5 }} />
            <Text style={[styles.sortText, { paddingTop: 5 }]}> 최신순  </Text>
        </TouchableOpacity>
        <TouchableOpacity style={{ flexDirection: 'row', paddingRight: 10 }} activeOpacity={0.8} onPress={this.abcSort}>
            <IconRadio name={this.state.abcRadioButtonChecked ? "check-circle" : "panorama-fish-eye"} size={20} color={'lightgrey'} style={{ paddingTop: 5 }} />
            <Text style={[styles.sortText, { paddingTop: 5 }]}> 가나다순</Text>
        </TouchableOpacity>
    </View>
</View>

MaterialIcon에서 check-circle ( 라디오버튼이 선택 된 상태 ) 과 panorama-fish-eye ( 빈 라디오버튼 )를 사용해주었습니다.


💡 최신순을 위한 sort

 response.sort((a,b)=>{ //최신순 sort
      return new Date(b.registerDate)-new Date(a.registerDate);
})

최신순을 알고있다면 오래된 순도 할 수 있겠죠 ?! 

 

- 다음에는 거리를 추가 후 거리순 정렬을 구현할 예정입니다