As we all know react native just launch its new 0.58 stable version but there is still a lot’s of components are missing and one of them is Checkbox. React native currently dose not provide us Checkbox component so we need to make our own custom checkbox. It is a two states handler button which can be checked and unchecked. Checkbox is used to get same type of multiple values from user in both android and iOS applications. Checkbox is very popular among developers because of its functionality to get multiple values from user. In this tutorial we would create Custom Checkbox Component for both iOS Android applications in react native.
Contents in this project React Native Custom Checkbox Component Example iOS Android:
1. We are handling the Checkbox checked functionality using a check image. So before going further please download the check image from below and put inside Your_React_Native_Project -> assets -> check.png . You need to manually create the assets folder in your react native project.
1 2 3 |
import React, { Component } from 'react'; import { Alert, Image, Platform, StyleSheet, Text, TouchableHighlight, View } from 'react-native'; |
3. Import PropTypes from prop-types in your project. We would create our custom props for Checkbox component. To use custom props in our project we need to import this. This library is come with react native project itself.
1 |
import PropTypes from 'prop-types'; |
4. Create a new class named as Selected_Items_Array. This class is used to manage the selected checkbox items into array.
pushItem : Method is used to push selected items into array.
getArray : returns us the selected items in array format.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class Selected_Items_Array { constructor() { selectedItemsArray = []; } pushItem(option) { selectedItemsArray.push(option); } getArray() { return selectedItemsArray; } } |
5. Create another class named as Checkbox. This class is our custom checkbox component class.
1 2 3 4 5 |
class Checkbox extends Component { } |
6. Create constructor method in Checkbox class. We are creating a state named as checked, this state is used to manage the checked and unchecked checkbox component states.
1 2 3 4 5 6 |
constructor() { super(); this.state = { checked: null } } |
7. Create componentWillMount() method in Checkbox class. Here we would check the state value and according to that call the pushItem() function of Selected_Items_Array class using props. Here we would Create 3 item value for Checkbox.
- key : Must be defined and should not be same. Managed by this.props.keyValue custom prop.
- label : The text shows with checkbox. Managed by this.props.label prop.
- value : Value which you want to get on checkbox selection. Managed by this.props.value prop.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
componentWillMount() { if (this.props.checked) { this.setState({ checked: true }, () => { this.props.selectedArrayObject.pushItem({ 'key': this.props.keyValue, 'label': this.props.label, 'value': this.props.value }); }); } else { this.setState({ checked: false }); } } |
8. Create a function named as toggleState() in Checkbox class. This function is used to manage the checkbox checked and unchecked state and also insert values in array when checkbox is checked.
1 2 3 4 5 6 7 8 9 10 |
toggleState(key, label, value) { this.setState({ checked: !this.state.checked }, () => { if (this.state.checked) { this.props.selectedArrayObject.pushItem({ 'key': key, 'label': label, 'value': value }); } else { this.props.selectedArrayObject.getArray().splice(this.props.selectedArrayObject.getArray().findIndex(x => x.key == key), 1); } }); } |
9. Creating the Checkbox view using TouchableHighlight component in render’s return block in in Checkbox class. We would call the toggleState function on onPress event of TouchableHighlight.
- this.props.size : Used to give custom width and height of checkbox component.
- this.props.color : Used to give the custom color of Checkbox.
- this.props.labelColor : Used to give the custom checkbox label color.
-
this.props.label : Used to give the label of checkbox.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
render() { return ( <TouchableHighlight onPress={this.toggleState.bind(this, this.props.keyValue, this.props.label, this.props.value)} underlayColor="transparent" style={{ marginVertical: 10 }}> <View style={{ flexDirection: 'row', alignItems: 'center' }}> <View style={{ width: this.props.size, height: this.props.size, backgroundColor: this.props.color, padding: 3 }}> { (this.state.checked) ? (<View style={styles.checkedView}> <Image source={require('./assets/check.png')} style={styles.checkBoxImage} /> </View>) : (<View style={styles.uncheckedView} />) } </View> <Text style={[styles.checkBoxLabelText, { color: this.props.labelColor }]}>{this.props.label}</Text> </View> </TouchableHighlight> ); } |
10. Complete source code for in Checkbox class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
class Checkbox extends Component { constructor() { super(); this.state = { checked: null } } componentWillMount() { if (this.props.checked) { this.setState({ checked: true }, () => { this.props.selectedArrayObject.pushItem({ 'key': this.props.keyValue, 'label': this.props.label, 'value': this.props.value }); }); } else { this.setState({ checked: false }); } } toggleState(key, label, value) { this.setState({ checked: !this.state.checked }, () => { if (this.state.checked) { this.props.selectedArrayObject.pushItem({ 'key': key, 'label': label, 'value': value }); } else { this.props.selectedArrayObject.getArray().splice(this.props.selectedArrayObject.getArray().findIndex(x => x.key == key), 1); } }); } render() { return ( <TouchableHighlight onPress={this.toggleState.bind(this, this.props.keyValue, this.props.label, this.props.value)} underlayColor="transparent" style={{ marginVertical: 10 }}> <View style={{ flexDirection: 'row', alignItems: 'center' }}> <View style={{ width: this.props.size, height: this.props.size, backgroundColor: this.props.color, padding: 3 }}> { (this.state.checked) ? (<View style={styles.checkedView}> <Image source={require('./assets/check.png')} style={styles.checkBoxImage} /> </View>) : (<View style={styles.uncheckedView} />) } </View> <Text style={[styles.checkBoxLabelText, { color: this.props.labelColor }]}>{this.props.label}</Text> </View> </TouchableHighlight> ); } } |
11. Create Constructor() in your main export default App class.
- selectedArrayOBJ : Object of Selected_Items_Array class.
- selectedItems : This state is used to print all the selected items of checkbox in Text component for demonstration purpose.
1 2 3 4 5 6 7 8 |
constructor() { super(); selectedArrayOBJ = new Selected_Items_Array(); this.state = { selectedItems: '' } } |
12. Create a function named as getSelectedItems() in your main export default App class. This function will call on The button on-press event and we would retrieve all the selected checkbox values in this function and store in selectedItems state.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
getSelectedItems = () => { if (selectedArrayOBJ.getArray().length == 0) { Alert.alert('No Items Selected!'); } else { // console.log(selectedArrayOBJ.getArray().map(item => item.label).join()); this.setState(() => { return { selectedItems: selectedArrayOBJ.getArray().map(item => item.value).join() } }); } } |
13. Create 3 Checkbox component in render’s return block of your main export default App class.
The Checkbox component has 8 different type of props available to modify it :
- size : Pass the value in number format. Set size of checkbox component.
- keyValue : Should not be same and used to manage the each checkbox individually in array.
- selectedArrayObject : Pass the object of Selected_Items_Array class.
- checked : By default check and un-check the checkbox. Support Boolean values.
- color : Pass the color in HEX color code. Used to change the color of checkbox.
- labelColor : Used to change the color of checkbox label color.
- label : Show the label text of checkbox.
- value : Which value you want to get on checkbox selection.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
render() { return ( <View style={styles.MainContainer}> <Checkbox size={30} keyValue={1} selectedArrayObject={selectedArrayOBJ} checked={true} color="#0091EA" labelColor="#0091EA" label="Item #1" value="item_1" /> <Checkbox size={35} keyValue={2} selectedArrayObject={selectedArrayOBJ} checked={true} color="#1B5E20" labelColor="#1B5E20" label="Item #2" value="item_2" /> <Checkbox size={40} keyValue={3} selectedArrayObject={selectedArrayOBJ} checked={true} color="#FF6F00" labelColor="#FF6F00" label="Item #3" value="item_3" /> <TouchableHighlight underlayColor="#000" style={styles.selectedItemsButton} onPress={this.getSelectedItems}> <Text style={styles.selectedItemsButton_Text}>Get Selected Items</Text> </TouchableHighlight> <Text style={{ fontSize: 20, color: "#000", marginTop: 20 }}> {this.state.selectedItems} </Text> </View> ); } |
14. Creating Style.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
const styles = StyleSheet.create( { MainContainer: { paddingTop: (Platform.OS === 'ios') ? 20 : 0, flex: 1, padding: 20, justifyContent: 'center', alignItems: 'center' }, selectedItemsButton: { marginTop: 25, padding: 8, backgroundColor: '#2962FF', alignSelf: 'stretch' }, selectedItemsButton_Text: { color: 'white', textAlign: 'center', alignSelf: 'stretch', fontSize: 18 }, checkedView: { flex: 1, justifyContent: 'center', alignItems: 'center' }, checkBoxImage: { height: '80%', width: '80%', tintColor: 'white', resizeMode: 'contain' }, uncheckedView: { flex: 1, backgroundColor: 'white' }, checkBoxLabelText: { fontSize: 16, paddingLeft: 10 } }); |
15. Defining props default values and their data holder type.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
Checkbox.propTypes = { size: PropTypes.number, keyValue: PropTypes.number.isRequired, selectedArrayObject: PropTypes.object.isRequired, color: PropTypes.string, label: PropTypes.string, labelColor: PropTypes.string, value: PropTypes.string, checked: PropTypes.bool } Checkbox.defaultProps = { size: 30, color: '#636c72', labelColor: '636c72', label: 'Default', checked: false, value: 'Default' } |
16. Complete source code for App.js File :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 |
import React, { Component } from 'react'; import { Alert, Image, Platform, StyleSheet, Text, TouchableHighlight, View } from 'react-native'; import PropTypes from 'prop-types'; class Selected_Items_Array { constructor() { selectedItemsArray = []; } pushItem(option) { selectedItemsArray.push(option); } getArray() { return selectedItemsArray; } } class Checkbox extends Component { constructor() { super(); this.state = { checked: null } } componentWillMount() { if (this.props.checked) { this.setState({ checked: true }, () => { this.props.selectedArrayObject.pushItem({ 'key': this.props.keyValue, 'label': this.props.label, 'value': this.props.value }); }); } else { this.setState({ checked: false }); } } toggleState(key, label, value) { this.setState({ checked: !this.state.checked }, () => { if (this.state.checked) { this.props.selectedArrayObject.pushItem({ 'key': key, 'label': label, 'value': value }); } else { this.props.selectedArrayObject.getArray().splice(this.props.selectedArrayObject.getArray().findIndex(x => x.key == key), 1); } }); } render() { return ( <TouchableHighlight onPress={this.toggleState.bind(this, this.props.keyValue, this.props.label, this.props.value)} underlayColor="transparent" style={{ marginVertical: 10 }}> <View style={{ flexDirection: 'row', alignItems: 'center' }}> <View style={{ width: this.props.size, height: this.props.size, backgroundColor: this.props.color, padding: 3 }}> { (this.state.checked) ? (<View style={styles.checkedView}> <Image source={require('./assets/check.png')} style={styles.checkBoxImage} /> </View>) : (<View style={styles.uncheckedView} />) } </View> <Text style={[styles.checkBoxLabelText, { color: this.props.labelColor }]}>{this.props.label}</Text> </View> </TouchableHighlight> ); } } export default class App extends Component { constructor() { super(); selectedArrayOBJ = new Selected_Items_Array(); this.state = { selectedItems: '' } } getSelectedItems = () => { if (selectedArrayOBJ.getArray().length == 0) { Alert.alert('No Items Selected!'); } else { // console.log(selectedArrayOBJ.getArray().map(item => item.label).join()); this.setState(() => { return { selectedItems: selectedArrayOBJ.getArray().map(item => item.value).join() } }); } } render() { return ( <View style={styles.MainContainer}> <Checkbox size={30} keyValue={1} selectedArrayObject={selectedArrayOBJ} checked={true} color="#0091EA" labelColor="#0091EA" label="Item #1" value="item_1" /> <Checkbox size={35} keyValue={2} selectedArrayObject={selectedArrayOBJ} checked={true} color="#1B5E20" labelColor="#1B5E20" label="Item #2" value="item_2" /> <Checkbox size={40} keyValue={3} selectedArrayObject={selectedArrayOBJ} checked={true} color="#FF6F00" labelColor="#FF6F00" label="Item #3" value="item_3" /> <TouchableHighlight underlayColor="#000" style={styles.selectedItemsButton} onPress={this.getSelectedItems}> <Text style={styles.selectedItemsButton_Text}>Get Selected Items</Text> </TouchableHighlight> <Text style={{ fontSize: 20, color: "#000", marginTop: 20 }}> {this.state.selectedItems} </Text> </View> ); } } const styles = StyleSheet.create( { MainContainer: { paddingTop: (Platform.OS === 'ios') ? 20 : 0, flex: 1, padding: 20, justifyContent: 'center', alignItems: 'center' }, selectedItemsButton: { marginTop: 25, padding: 8, backgroundColor: '#2962FF', alignSelf: 'stretch' }, selectedItemsButton_Text: { color: 'white', textAlign: 'center', alignSelf: 'stretch', fontSize: 18 }, checkedView: { flex: 1, justifyContent: 'center', alignItems: 'center' }, checkBoxImage: { height: '80%', width: '80%', tintColor: 'white', resizeMode: 'contain' }, uncheckedView: { flex: 1, backgroundColor: 'white' }, checkBoxLabelText: { fontSize: 16, paddingLeft: 10 } }); Checkbox.propTypes = { size: PropTypes.number, keyValue: PropTypes.number.isRequired, selectedArrayObject: PropTypes.object.isRequired, color: PropTypes.string, label: PropTypes.string, labelColor: PropTypes.string, value: PropTypes.string, checked: PropTypes.bool } Checkbox.defaultProps = { size: 30, color: '#636c72', labelColor: '636c72', label: 'Default', checked: false, value: 'Default' } |
Screenshots:
nice tutorial sir
Thanks Rahul 🙂 .
hii sir, make a tutorial on when scroll down to hide search bar and when scroll up to show search bar with flatList
Hi ..let say i have three check box i.e. Android,Ios and Both
We can change the state of check box one at a time.If i click on both then rest two check box will be checked.How to do that? please help
Please explain your question more briefly.
Hi thanks for your reply.
I have three options as check box
1> Android
2> Ios
3> Both
When we select option no 3 then option no 1 and option no 2 will
also select .
But i m unable to do that.Please help.
Simply put a condition and check if user select BOTH then automatically add above both values.
But how to add both values.I am new in React
toggleState(key, label, value) {
if(value==’Both’){
// can’t add logic here.Please add some code snippet
}
else{
this.setState({ checked: !this.state.checked }, () => {
if (this.state.checked) {
this.props.selectedArrayObject.pushItem({ ‘key’: key, ‘label’: label, ‘value’: value });
}
else {
this.props.selectedArrayObject.getArray().splice(this.props.selectedArrayObject.getArray().findIndex(x => x.key == key), 1);
console.log(‘unchecked’)
}
});
}
}