ReactNative checkBoxについて
チェックボックスの追加
まずReactNativeでcheckBoxは標準機能でないそうです。
そのためこちらのチェックボックスを使用したいと思います。
まず、下記コマンドでチェックボックスをインストールしてください。
npx expo install expo-checkbox
そうすることでexpoのcheckboxをインポートできます。
import Checkbox from 'expo-checkbox';
チェックボックスが押された時の状態更新処理(isCheckedの反転)を書きます。
const toggleTodo = (index: number) => {
setTodos(prev =>
prev.map((todo, i) =>
i == index
? { ...todo, isChecked: !todo.isChecked }
: todo
)
);
};
mapでtodoの配列を回し、押されたindexのisCheckedを反転させるようにしています。
todoインターフェースにisCheckedを追加していきます。
interface Todo {
title: string;
dueDate: DateType;
isChecked: boolean;
}
todoを新規作成時にはisCheckedにfalseを入れておきます。
const newTodo: Todo = {
title: trimmed,
dueDate: due,
isChecked: false,
};
作成したCheckboxをViewに追加します。
<Checkbox
style={{ marginRight: 12 }}
value={item.isChecked}
onValueChange={() => toggleTodo(todos.indexOf(item))}
color={item.isChecked ? '#28a745' : undefined}
/>
Todoを「未完了」と「完了済み」で分けて表示
区切り線
区切り線のコンポーネントの追加
// 横線コンポーネント
const HorizontalLine = (
<View style={{ height: 1, backgroundColor: '#e9ecef', marginVertical: 12 }} />
);
Todo配列の分割
// Todoを分割
const uncheckedTodos = todos.filter(todo => !todo.isChecked);
const checkedTodos = todos.filter(todo => todo.isChecked);
未完了Todoのリスト表示
<FlatList
data={uncheckedTodos}
完了済みTodoのリスト表示と区切り線も表示
{/* 横線 */}
{checkedTodos.length > 0 && HorizontalLine}
{/* 完了済みTodoリスト */}
<FlatList
data={checkedTodos}
keyExtractor={(item, index) => `checked-${item.title}-${index}`}
renderItem={({ item, index }) => (
<View
style={{
backgroundColor: '#f8f9fa',
borderRadius: 8,
borderWidth: 1,
borderColor: '#e9ecef',
padding: 12,
marginBottom: 8,
flexDirection: 'row',
alignItems: 'center',
opacity: 0.6,
}}
>
<Checkbox
style={{ marginRight: 12 }}
value={item.isChecked}
onValueChange={() => toggleTodo(todos.indexOf(item))}
color={item.isChecked ? '#28a745' : undefined}
/>
<View style={{ flex: 1 }}>
<Text style={{
fontSize: 16,
color: '#212529',
fontWeight: '600',
marginBottom: 4,
textDecorationLine: 'line-through',
}}>
{item.title}
</Text>
<Text style={{ fontSize: 14, color: '#6c757d' }}>
期限: {formatDate(item.dueDate)}
</Text>
</View>
</View>
)}
/>
カスタムチェックボックス
まずチェックボックスを四角形から丸型にし、色を水色にしようとし、失敗しました。
<Checkbox
style={{
marginRight: 12,
width: 22,
height: 22,
borderWidth: 2,
borderColor: item.isChecked ? '#5bcaf3ff' : '#bbb',
backgroundColor: item.isChecked ? '#5bcaf3ff' : '#fff',
justifyContent: 'center',
alignItems: 'center',
}}
value={item.isChecked}
onValueChange={() => toggleTodo(todos.indexOf(item))}
color="#5bcaf3ff"
/>
こちらが変更しようとしたコードになります。
原因はexpo-checkboxがNativeのコンポーネントを利用しているため、スタイルを変更することができないそうです。
時間がある時に丸型のチェックボックスもチャレンジしたいと思います。



