I have been able to add item in onPress but it only shows the pressed item only. I want it to displays all the selected item in a row in the view beneath.
const [text, setText] = useState([]);
const numbers =['1','2','4', '5', '6', '7', '8', '9', '10','11','12','13','14','15','16','17','18','19']
const onPress =(item)=>{ setText(<Text style={{textAlign:"center"}}>{item}); console.log(item) };
return (
<View style={styles.container}>
<ScrollView>
<View style={{flexDirection: 'row',flexWrap: 'wrap', justifyContent:"center"}}>
{numbers.map((item, index) => {
return (
<TouchableOpacity style={styles.item} onPress={()=>onPress(item)}>
<Text style={{textAlign:"center"}} key={index}> {item}</Text>
</TouchableOpacity>
)})}
</View>
<View style={styles.select}>{text}</View>
</ScrollView>
</View>
The problem with your current code is that your onPress will override the previous value instead of appending to it. To append previous values into your text, you will need to first destructure the text state in your onPress followed by the new number.
const onPress = (item) => setText(oldText => {
if (oldText.length < max) {
return [...oldText, item]
} else return oldText
})