0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[React Native] Flatlistのitemごとにstyleを設定する

Last updated at Posted at 2022-01-23

Flatlistのitemごとにstyle適応

● 概要

ReactNative でFlatlistを作成する際に item ごとに style 設定したかったのでその内容を自分なりにまとめてみました。

● 実行環境

  • Expo Snack

● コード

import React from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text, StatusBar } from 'react-native';

const DATA = [
  {
    id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
    title: 'First Item',
  },
  {
    id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
    title: 'Second Item',
  },
  {
    id: '58694a0f-3da1-471f-bd96-145571e29d72',
    title: 'Third Item',
  },
];

let itemStyle1 = {color: 'red',backgroundColor: '#96daff'};
let itemStyle2 = {color: 'black',backgroundColor: 'pink'};
let itemStyle;

//DATAのtitleごとにstyleを設定
function divideStyle (word) {
  if(word.title =='First Item') {
      itemStyle = itemStyle1
    }
  else{
      itemStyle = itemStyle2
  }
  return itemStyle
}

const Item = ({ title }) => (
  <View style={styles.item}>
    <Text style={divideStyle({title})}>{title}</Text>
  </View>
);

const App = () => {
  const renderItem = ({ item }) => (
    <Item title={item.title} />
  );

  return (
    <SafeAreaView style={styles.container}>
      <FlatList
        data={DATA}
        renderItem={renderItem}
        keyExtractor={item => item.id}
      />
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    marginTop: StatusBar.currentHeight || 0,
  },
  item: {
    backgroundColor: '#acafb3',
    padding: 10,
    marginVertical: 8,
    marginHorizontal: 16,
  },
});

export default App;

● ポイント

関数 divideStyle() でDATAのtitleごとにstyleを設定。

今回は DATA の title が

・First Item'だった場合: Flatlist 内のitemに itemStyle1 = {color: 'red',backgroundColor: '#96daff'};

・それ以外の場合: Flatlist 内の item に itemStyle2 = {color: 'black',backgroundColor: 'pink'};

を適応させています。

##● 実行結果

2022-01-23 13_04_38-.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?