Reputation: 1044
I'm new to react native and i am trying to make a text selection with checkmark and select only one Text Element , do i have to use button instead ?
React Code
<View style={styles.mainContainer}>
<Text style={styles.title}>User Role</Text>
<View style={styles.detailsContainer}>
<View style={styles.rowContainer}>
<Text style={styles.row}>Admin</Text>
</View>
<View style={styles.rowContainer}>
<Text style={styles.row}>Assistant</Text>
</View>
</View>
</View>
Stylesheet
mainContainer: {
marginTop: 20,
},
detailsContainer: {
backgroundColor: '#FFF',
marginTop: 10,
},
title: {
paddingLeft: 16,
color: '#979797',
textTransform: 'uppercase',
},
Upvotes: 5
Views: 2919
Reputation: 3150
You must use TouchableOpacity
from react-native and Icon from react-native-elements
and then do this.
<View style={styles.mainContainer}>
<Text style={styles.title}>User Role</Text>
<View style={styles.detailsContainer}>
<TouchableOpacity
style={styles.rowContainer}
onPress={() => {
this.setState({ adminIsChecked: true, assistantIsChecked: false });
}}
>
<View style={{ flexDirection: 'row' }}>
<Text style={styles.row}>Admin</Text>
{this.state.adminIsChecked ?
(<Icon name='check' />)
:
(null)
}
</View>
</TouchableOpacity>
<TouchableOpacity
style={styles.rowContainer}
onPress={() => {
this.setState({ assistantIsChecked: true, adminIsChecked: false });
}}
>
<View style={{ flexDirection: 'row' }}>
<Text style={styles.row}>Assistant</Text>
{this.state.assistantIsChecked ?
(<Icon name='check' />)
:
(null)
}
</View>
</TouchableOpacity>
</View>
</View>
The onPress()
of Touchable items receives a trigger when they are pressed triggering the function you have been defined in.
We will have checked one item if it state is checked, making them checked when onPress
is called and, obviously, unchecking the other one.
To use change states of the app we use this.setState()
and to get the state this.state
. If you are lost about state, I recommend you to read about it first here.
Upvotes: 2
Reputation: 5186
You need to take a variable on hold the selected item from list.
state = {
selectedId: null
}
renderItem({ item }) {
return (
<TouchableOpacity
onPress={() => {
this.setState({
selectedId: item.id
})
}}>
<View style={styles.mainContainer} >
<Text style={styles.title}>User Role</Text>
<View style={styles.detailsContainer}>
<View style={styles.rowContainer}>
<Text style={styles.row}>Admin</Text>
</View>
<View style={styles.rowContainer}>
<Text style={styles.row}>Assistant</Text>
</View>
</View>
{
this.state.selectedId === item.id ? <CHECK_MARK_IMAGE /> : null
}
</View>
</TouchableOpacity>
)
}
I am hoping that you are putting your react native code into one method.
Upvotes: 1