Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

React Native SectionList 완벽 가이드: 개념부터 실전 예제까지

SectionList는 데이터를 섹션(그룹) 단위로 나누어 리스트 형태로 화면에 렌더링할 수 있게 도와주는 React Native 컴포넌트입니다. 연락처 앱이나 설정 메뉴처럼 항목을 카테고리별로 묶어 보여줘야 할 때 특히 유용합니다.

SectionList의 주요 기능

  • 리스트 전체에 헤더(Header) / 푸터(Footer) 지원
  • 각 섹션별 헤더 / 푸터 지원
  • 스크롤 시 데이터 로딩(Scroll Loading)
  • 당겨서 새로고침(Pull to Refresh)
  • iOS와 Android 모두에서 동작하는 완전한 크로스 플랫폼 지원

SectionList의 기본적인 사용 구조는 다음과 같습니다.

<SectionList sections={DataContainer} keyExtractor={yourkeyextractor} renderItem={yourenderItem} renderSectionHeader={yoursectionheader} />

SectionList를 사용하려면 먼저 react-native에서 컴포넌트를 임포트해야 합니다.

import { SectionList } from "react-native";

SectionList의 주요 Props 정리

Props설명
renderItem섹션 내 각 항목을 렌더링하는 기본 함수입니다. React 엘리먼트를 반환하며, 다음 키들을 가진 객체가 전달됩니다.
- item(object): 렌더링할 항목 객체
- index(number): 섹션 내 항목의 인덱스
- section(object): 해당 섹션 객체
- separators(object): 구분선 관련 객체로 아래 키들을 포함합니다.
  · highlight (function): () => void
  · unhighlight (function): () => void
  · updateProps (function): (select, newProps) => void
  · select (enum): 'leading' 또는 'trailing'
  · newProps (object)
sections렌더링할 실제 데이터 배열입니다.
renderSectionHeader각 섹션 상단에 렌더링되는 콘텐츠입니다. iOS에서는 스크롤 시 섹션 헤더가 상단에 고정되는(docking) 효과를 볼 수 있습니다.
renderSectionFooter각 섹션 하단에 렌더링되는 콘텐츠입니다.
refreshing새로고침 중 새 데이터를 렌더링해야 할 때 true로 설정합니다.
ListEmptyComponent리스트가 비어 있을 때 호출되는 컴포넌트 클래스, 렌더 함수 또는 렌더 엘리먼트입니다. 빈 목록 상황에서 안내 메시지 등을 보여줄 때 유용합니다.
ListFooterComponent모든 항목 하단에 렌더링되는 컴포넌트 클래스, 렌더 함수 또는 렌더 엘리먼트입니다.
ListFooterComponentStyle푸터 컴포넌트에 적용할 스타일을 지정합니다.
ListHeaderComponent모든 항목 상단에 렌더링되는 컴포넌트 클래스, 렌더 함수 또는 렌더 엘리먼트입니다.
ListHeaderComponentStyle헤더 컴포넌트에 적용할 스타일을 지정합니다.
keyExtractor주어진 인덱스에 대한 고유 키를 추출합니다. 이 키는 캐싱 및 항목 재정렬 추적에 사용됩니다.

예제 1: SectionList로 데이터 표시하기

먼저 필요한 컴포넌트들을 임포트합니다.

import { SectionList , Text, View, StyleSheet} from "react-native";

임포트가 끝나면 SectionList에 표시할 데이터가 필요합니다. 여기서는 this.state.data에 섹션별 데이터를 저장합니다.

this.state = {
    data: [
        {
            title: "Javascript Frameworks",
            data: ["Angular", "ReactJS", "VueJS", "ReactNative"]
        },
        {
            title: "PHP Frameworks",
            data: ["Laravel", "CodeIgniter", "CakePHP", "Symfony"]
        }
    ]
};

renderItem 함수 구현

아래 함수는 전달받은 항목(item)을 Text 컴포넌트로 화면에 표시하는 역할을 합니다.

renderItem = ({ item }) => {
    return (
        <View style={styles.item}>
            <Text>
                {item}
            </Text>
        </View>
    );
};

Text 컴포넌트가 항목을 표시하고, 이를 View 컴포넌트가 감싸는 구조입니다.

SectionList 구현하기

다음은 sections, renderItem, keyExtractor, renderSectionHeader props를 사용한 SectionList 구현 예제입니다.

<View style={styles.container}>
    <SectionList
        sections={this.state.data}
        renderItem={this.renderItem}
        keyExtractor={(item, index) => index}
        renderSectionHeader={({ section: { title } }) => (
            <Text style={styles.header}>{title}</Text>
        )}
    />
</View>

this.state.datasections props에 전달되고, this.renderItem 함수는 renderItem props에 할당됩니다.

데이터 배열에서 고유한 값을 가지는 속성이 있다면 그것을 keyExtractor props에 지정하는 것이 좋습니다. 별도로 지정하지 않으면 배열 인덱스가 key 값으로 사용됩니다.

여기서는 item과 index를 조합한 값(item + index)을 고유 키로 사용했습니다.

keyExtractor={(item, index) => item + index}

renderSectionHeader props는 각 섹션의 헤더(제목)를 표시하는 역할을 담당합니다.

아래는 위 내용을 모두 합친 전체 코드입니다.

import React from "react";
import { SectionList , Text, View, StyleSheet} from "react-native";
export default class App extends React.Component {
    constructor() {
        super();
        this.state = {
            data: [
                {
                    title: "Javascript Frameworks",
                    data: ["Angular", "ReactJS", "VueJS", "ReactNative"]
                },
                {
                    title: "PHP Frameworks",
                    data: ["Laravel", "CodeIgniter", "CakePHP", "Symfony"]
                }
            ]
        };
    }
    renderItem = ({ item }) => {
        return (
            <View style={styles.item}>
                <Text>
                    {item}
                </Text>
            </View>
        );
    };
    render() {
        return (
            <View style={styles.container}>
                <SectionList
                    sections={this.state.data}
                    renderItem={this.renderItem}
                    keyExtractor={(item, index) => index}
                    renderSectionHeader={({ section: { title } }) => (
                        <Text style={styles.header}>{title}</Text>
                    )}
                />
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginTop: 20,
        marginHorizontal: 16
    },
    item: {
        backgroundColor: "#ccc2ff",
        padding: 20,
        marginVertical: 8
    },
    header: {
        fontSize: 32,
        backgroundColor: "#fff"
    }
});

실행 결과

React Native SectionList 완벽 가이드: 개념부터 실전 예제까지

예제 2: stickySectionHeadersEnabled로 섹션 헤더 고정하기

stickySectionHeadersEnabled props를 사용하면 SectionList의 섹션 헤더를 화면 상단에 고정(sticky)할 수 있습니다. 사용자가 스크롤해서 다음 섹션 헤더가 화면 상단에 도달하면 해당 헤더가 상단에 붙어 고정되며, 이 동작이 모든 섹션 헤더에 반복적으로 적용됩니다.

import React from "react";
import { SectionList , Text, View, StyleSheet} from "react-native";
export default class App extends React.Component {
    constructor() {
        super();
        this.state = {
            data: [
                {
                    title: "Javascript Frameworks",
                    data: ["Angular", "ReactJS", "VueJS", "ReactNative"]
                },
                {
                    title: "PHP Frameworks",
                    data: ["Laravel", "CodeIgniter", "CakePHP", "Symfony"]
                },
                {
                    title: "Apache Frameworks",
                    data: ["Apache Flex", "Apache Crunch", "Apache CouchDB", "Apache Crail"]
                }
            ]
        };
    }
    renderItem = ({ item }) => {
        return (
            <View style={styles.item}>
                <Text>
                    {item}
                </Text>
            </View>
        );
    };
    render() {
        return (
            <View style={styles.container}>
                <SectionList
                    stickySectionHeadersEnabled={true}
                    sections={this.state.data}
                    renderItem={this.renderItem}
                    keyExtractor={(item, index) => index}
                    renderSectionHeader={({ section: { title } }) => (
                        <Text style={styles.header}>{title}</Text>
                    )}
                />
            </View>
        );
    }
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        marginTop: 20,
        marginHorizontal: 16
    },
    item: {
        backgroundColor: "#ccc2ff",
        padding: 20,
        marginVertical: 8
    },
    header: {
        fontSize: 32,
        backgroundColor: "#fff"
    }
});

실행 결과

React Native SectionList 완벽 가이드: 개념부터 실전 예제까지