How to useState hooks with array - javascript

I am not able to push the number index in the array of useState.
Where I am going wrong, do I want to push the index of numbers when I click them?
I am extracting the previous state array and then I push new but nothing happens.
How to push a new element inside useState array React hook? My code doesn't work!!
Please someone check.
Game.js
import { StatusBar } from "expo-status-bar";
import React, { useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import RandomNumber from "./RandomNumber";
export default function Game(props) {
const [state, setstate] = useState([]);
let randomNumber = Array.from({ length: props.randomNumberCount }).map(
() => 1 + Math.floor(10 * Math.random())
);
let target = randomNumber
.slice(0, props.randomNumberCount - 2)
.reduce((acc, curr) => acc + curr, 0);
const isNumberSelected = (numberIndex) => {
return state.indexOf(numberIndex) >= 0;
};
const selectNumber = (numberIndex) => {
setstate((arr) => [...arr, numberIndex]);
};
return (
<View style={styles.container}>
<Text style={styles.header}>Target Sum Game</Text>
<Text style={styles.target}>{target}</Text>
<View style={styles.randomContainer}>
{randomNumber.map((randomNumber, index) => (
<RandomNumber
key={index}
id={index}
number={randomNumber}
isSelected={isNumberSelected(index)}
onClick={() => selectNumber}
/>
))}
</View>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#ddd",
paddingTop: 30,
},
target: {
fontSize: 30,
backgroundColor: "#aaa",
margin: 50,
marginHorizontal: 70,
textAlign: "center",
},
header: {
fontSize: 35,
backgroundColor: "dodgerblue",
textAlign: "center",
marginHorizontal: 30,
marginTop: 50,
},
randomContainer: {
flexDirection: "row",
flexWrap: "wrap",
justifyContent: "space-around",
},
});
RandomNumber.js
import React from "react";
import { StyleSheet, Text, TouchableOpacity } from "react-native";
export default function RandomNumber(props) {
const handlePress = () => {
props.onClick(props.id);
};
return (
<TouchableOpacity onPress={handlePress()}>
<Text style={[styles.random, props.isSelected && styles.selected]}>
{props.number}
</Text>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
random: {
backgroundColor: "#999",
width: 100,
marginHorizontal: 35,
marginVertical: 25,
fontSize: 35,
textAlign: "center",
},
selected: {
opacity: 0.3,
},
});

you are not calling the function
onClick={() => selectNumber(index)}

You need to change the onClick prop and pass the randomNumber (or index depending of what you want to do) to the selectNumber function:
// Not sure if you want to pass randonNumber or index but you get the idea
onClick={() => selectNumber(randomNumber)}

<TouchableOpacity onPress={handlePress()}>
should be
<TouchableOpacity onPress={()=>handlePress()}>
and
() => selectNumber
should be
() => selectNumber()
please try it

Might Be This Helpful:
Home.Js
import React, {useState, useEffect} from 'react';
import {StyleSheet, Text, View, TouchableOpacity} from 'react-native';
import RandomNumber from './RandomNumber';
const Home = props => {
const [state, setstate] = useState([]);
useEffect(() => {
console.log('state', state);
}, [state]);
let randomNumber = Array.from({length: 10}).map(
() => 1 + Math.floor(10 * Math.random()),
);
let target = randomNumber
.slice(0, props.randomNumberCount - 2)
.reduce((acc, curr) => acc + curr, 0);
const isNumberSelected = numberIndex => {
return state.indexOf(numberIndex) >= 0;
};
const selectNumber = numberIndex => {
console.log('numberIndex', numberIndex);
setstate(arr => [...arr, numberIndex]);
};
return (
<View style={styles.container}>
<Text style={styles.header}>Target Sum Game</Text>
<Text style={styles.target}>{target}</Text>
<View style={styles.randomContainer}>
{randomNumber.map((randomNumber, index) => {
return (
<RandomNumber
key={index}
id={index}
number={randomNumber}
isSelected={isNumberSelected(index)}
onClick={() => selectNumber(randomNumber)}
/>
);
})}
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#ddd',
paddingTop: 30,
},
target: {
fontSize: 30,
backgroundColor: '#aaa',
margin: 50,
marginHorizontal: 70,
textAlign: 'center',
},
header: {
fontSize: 35,
backgroundColor: 'dodgerblue',
textAlign: 'center',
marginHorizontal: 30,
marginTop: 50,
},
randomContainer: {},
});
export default Home;
RandomNumber.js
import React from 'react';
import {StyleSheet, Text, View, TouchableOpacity} from 'react-native';
export default function RandomNumber(props) {
const handlePress = () => {
props.onClick(props.id);
};
return (
<View style={{}}>
<TouchableOpacity onPress={() => handlePress()}>
<Text style={[styles.random, props.isSelected && styles.selected]}>
{props.number}
</Text>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
random: {
backgroundColor: '#999',
width: 100,
height: 100,
marginHorizontal: 35,
marginVertical: 25,
fontSize: 35,
textAlign: 'center',
},
selected: {
opacity: 0.3,
},
});
Output Log:

Related

How to use react-native-vision-camera instead of expo-camer?

How to use react-native-vision-camera instead of expo-camera? earlier I was developing my project in expo but currently I am developing it using react native cli can anyone can tell me how can I use this package call react-native-vision-camera and make it work same as my expo code with any errors I tried using myself my it was giving me a black screen In my case android
Expo Code:
import { Camera } from 'expo-camera';
import { TouchableOpacity, Text, View, ActivityIndicator } from 'react-native';
import { useState, useEffect, useRef } from "react";
import * as FaceDetector from 'expo-face-detector';
export default function CameraPage({ navigation }) {
const [hasPermission, setHasPermission] = useState(null);
const cameraRef = useRef(null);
const [faceData, setFaceData] = useState([]);
useEffect(() => {
(async () => {
const { status } = await Camera.requestCameraPermissionsAsync();
setHasPermission(status === 'granted');
})();
}, []);
if (hasPermission === null) {
return <View />;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
const handleTakePicture = async () => {
if (faceData.length === 0) {
alert('No Face')
}
else if
(cameraRef.current) {
const photo = await cameraRef.current.takePictureAsync();
console.log(photo.uri)
if (!photo.cancelled) {
navigation.navigate('addphoto', { Image: photo.uri });
}
}
}
const handleFacesDetected = ({ faces }) => {
setFaceData(faces);
}
return (
<View style={{ flex: 1, backgroundColor: 'black' }}>
<Camera
onFacesDetected={handleFacesDetected}
faceDetectorSettings={{
mode: FaceDetector.FaceDetectorMode.fast,
detectLandmarks: FaceDetector.FaceDetectorLandmarks.none,
runClassifications: FaceDetector.FaceDetectorClassifications.none,
minDetectionInterval: 100,
tracking: true,
}}
style={{
borderTopLeftRadius: 30,
borderTopRightRadius: 30,
borderBottomLeftRadius: 30,
borderBottomRightRadius: 30,
overflow: 'hidden',
width: '130%',
aspectRatio: 1,
}}
type={Camera.Constants.Type.front}
ref={cameraRef}
>
<View style={{ flex: 1, backgroundColor: 'transparent', flexDirection: 'row' }}>
</View>
</Camera>
<TouchableOpacity
style={{
alignSelf: 'center',
alignItems: 'center',
width: 90,
height: 90,
borderRadius: 500,
marginTop: '30%',
marginLeft: '5%',
borderColor: '#5A5A5A',
borderWidth: 6,
}}
onPress={handleTakePicture}
>
<View style={{ opacity: 0.5 }} />
</TouchableOpacity>
</View>
);
}

getByTestId Not Finding TestID

As I mentioned in some of my prior posts, I am new to testing React Native apps. I am trying to test this function that checks if a person is over 21 years old. I am experiment with the React Native testing to see where I should test components, so currently I put them on two elements arbitrarily. However, when I go to get the element by testID, it says that that the testID cannot be found. Below is where I have them currently/initially -- I moved them around to other locations and was yielding the same response. The test scripts are below:
import '../../../matchMedia.mock';
import React from 'react';
import renderer, { act } from 'react-test-renderer';
import VerificationScreen from '../VerificationScreen';
import { RecoilRoot } from 'recoil';
import { render, fireEvent, screen } from '#testing-library/react-native'
import ReactDOM from 'react-dom';
const mockNavigation = {
navigate: jest.fn(),
addListener: jest.fn()
}
test('renders correctly', () => {
const tree = renderer.create(<RecoilRoot><VerificationScreen navigation= {mockNavigation}/></RecoilRoot>).toJSON();
expect(tree).toMatchSnapshot();
});
test('renders default elements', () => {
const { getAllByText } = render(<RecoilRoot><VerificationScreen navigation= {mockNavigation}/></RecoilRoot>);
expect(getAllByText('Can I see some ID?').length).toBe(1);
expect(getAllByText('You must be of legal drinking age to use this app.').length).toBe(1);
expect(getAllByText('Enter Now').length).toBe(1);
});
test('display error if the user is not 21', () => {
const { getAllByText } = render(<RecoilRoot><VerificationScreen navigation= {mockNavigation}/></RecoilRoot>);
console.log(getAllByText('MMDDYYYY'));
fireEvent.changeText(queryByTestId('Verification.DOB'), '10012021');
fireEvent.press(getByTestId('Verification.Submit'));
})
The component itself is below:
import React from 'react';
import moment from 'moment';
import { View, Text, StyleSheet, TouchableOpacity, TextInput } from 'react-native';
import { COLORS } from '../../styles/COLORS';
import { SHADOWS } from '../../styles/shadows';
import ClickableText from '../widgets/ClickableText';
import Logo from '../widgets/Logo';
import SlideInContainer from '../widgets/SlideInContainer';
import Spacing from '../widgets/Spacing';
import ErrorToast from '../widgets/ErrorToast';
import { handleError } from '../utils/ErrorFunctions';
import useDateOfBirth from './useDateOfBirth';
import setStatusBarColor from '../utils/StatusBarColorFunctions';
const VerificationScreen = ({ navigation }) => {
const [error, setError] = React.useState(null);
const [dateOfBirth, setDateOfBirth] = useDateOfBirth();
const [text, setText] = React.useState(dateOfBirth);
const [inputFocused, setInputFocused] = React.useState(false);
const [setColor] = setStatusBarColor();
const DATE_LENGTH = 8;
const ref = React.useRef(null);
const handleOnPress = () => {
setInputFocused(true);
ref.current.focus();
};
const handleOnBlur = () => {
setInputFocused(false);
};
const onSubmit = () => {
// add validation
if (text.length === DATE_LENGTH) {
const MM = text.substring(0, 2);
const DD = text.substring(2, 4);
const YYYY = text.substring(4);
const years = moment(new Date())
.diff(`${YYYY}-${MM}-${DD}`,
'years', false);
if (years >= 21) {
setDateOfBirth(text);
navigation.navigate('Home');
} else {
handleError('Error: You must be 21 to use this app', setError);
}
} else {
handleError('Error: Please input a valid date', setError);
}
};
React.useEffect(() => {
if (dateOfBirth !== '') {
setText(dateOfBirth);
}
}, [dateOfBirth]);
React.useEffect(() => {
setColor(COLORS.red);
},[])
return (
<View style={styles.container}>
<View style={styles.alignment}>
<TextInput
ref={ref}
value={text}
onChangeText={setText}
onBlur={handleOnBlur}
keyboardType="number-pad"
returnKeyType="done"
textContentType="oneTimeCode"
maxLength={DATE_LENGTH}
style={styles.hidden} />
<SlideInContainer>
<ErrorToast
error={error} />
<Logo />
<Text style={styles.title}>Can I see some ID?</Text>
<Text style={styles.subtitle}>You must be of legal drinking age to use this app.</Text>
<TouchableOpacity
style={styles.dateInputContainer}
onPress={() => handleOnPress()}
activeOpacity={1}>
<Text
style={styles.dateText}
testID='Verification.DOB'>
{'MMDDYYYY'.split('').map((val, i) => {
let ret = '';
if (i < text.length) {
ret = text.charAt(i);
} else {
ret = val;
}
if (i === 1 || i === 3) {
ret += '/';
}
return ret;
})}
</Text>
</TouchableOpacity>
<TouchableOpacity
testID='Verification.Submit'
onPress={() => onSubmit()}
style={styles.buttonContainer}>
<Text style={styles.buttonText}>
Enter Now
</Text>
</TouchableOpacity>
<Spacing vertical={10} />
<Text style={styles.legalText}>By entering this app you are agreeing to our <ClickableText text="Terms of Service" url="https://www.google.com" /> and <ClickableText text="Privacy Policy" url="https://www.google.com" /> </Text>
</SlideInContainer>
</View>
<Text style={styles.disclaimerText}>
You must be at least 21 years of age to drink alcoholic beverages. Do not drink and drive, drink to excess or drink with certain medications or medical conditions. For more information, please visit <ClickableText text="this website" url="http://www.cdc.gov/alcohol/index.htm"/> or contact your health provider.
</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: COLORS.red,
},
noteContainer: {
position: 'absolute',
bottom: 0,
},
alignment: {
flex: 0.65
},
hidden: {
opacity: 0,
},
title: {
fontFamily: 'open-sans-semi',
fontSize: 18,
},
subtitle: {
fontFamily: 'open-sans',
textAlign: 'center',
paddingHorizontal: 8,
fontSize: 15,
paddingTop: 8
},
dateInputContainer: {
padding: 20
},
dateText: {
fontSize: 30,
fontFamily: 'open-sans',
},
buttonContainer: {
backgroundColor: COLORS.green,
paddingVertical: 5,
paddingHorizontal: 35,
borderRadius: 5,
...SHADOWS.button,
},
buttonText: {
color: COLORS.white,
fontSize: 18,
fontFamily: 'open-sans-semi',
},
legalText: {
fontFamily: 'open-sans',
paddingBottom: 20,
paddingHorizontal: 8,
fontSize: 12,
textAlign: 'center'
},
disclaimerText: {
fontFamily: 'open-sans',
fontSize: 12,
position: 'absolute',
bottom: 0,
textAlign: 'center',
justifyContent: 'center'
}
})
export default VerificationScreen;
If additional information is needed, please let me know. Thanks in advance!
You are gettinge rror becaue it cant' find TouchablOpacity. Try to mock it at the top like this-
jest.mock('TouchableOpacity', () => 'TouchableOpacity')

React native `input` must be a function received undefined

I have an array which displays a list of jobs with the radio button(each).If I click any radio button I want to get its value so far I'm getting an error input must be a function received undefined. how can I achieve something like this in react native?
Code
import React, {useState} from 'react';
import {View, Text, TextInput, Image,Button,Body,Pressable,ScrollView,Switch} from 'react-native';
export default function Home({ navigation}){
let roles = navigation.getParam('roles')
const [isEnabled, setIsEnabled] = useState(false);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
const handleClick = (data, e) => {
alert(e.target.value, data);
}
<View>
{
Object.keys(roles).map((key) => {
return (
<View>
<View style={styles.XYQHC}>
<Text>{roles[key]['name']}</Text>
<Switch
trackColor={{ false: "#767577", true: "#81b0ff" }}
thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
ios_backgroundColor="#3e3e3e"
onValueChange={toggleSwitch}
value={isEnabled}
/>
<input type="radio" name="roles" value={roles[key]['name']} defaultChecked={roles[key]['id'] == 3 ? true : false } onClick={handleClick.bind(this, roles[key]['name'])}/>
</View>
</View>
)
})
}
</View>
};
I had to edit a little bit to make it work and to assume some input data but here is a working example of your code:
import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
function RadioButton({ label, onPress, selected, style }) {
return (
<TouchableOpacity
style={[
{
flexDirection: 'row',
alignItems: 'center',
marginLeft: 12,
marginVertical: 20,
},
style,
]}
onPress={onPress}>
<View
style={{
height: 24,
width: 24,
borderRadius: 12,
borderWidth: 2,
borderColor: '#000',
alignItems: 'center',
justifyContent: 'center',
marginRight: 12,
}}>
{selected ? (
<View
style={{
height: 12,
width: 12,
borderRadius: 6,
backgroundColor: '#000',
}}
/>
) : null}
</View>
<Text>{label}</Text>
</TouchableOpacity>
);
}
export default function Home({ navigation }) {
// let status = navigation.getParam('status');
let status = 2;
// let roles = navigation.getParam('roles');
let roles = [
{
id: 1,
name: 'lawyer',
},
{
id: 2,
name: 'farmer',
},
{
id: 3,
name: 'architect',
},
];
const [isEnabled, setIsEnabled] = useState(false);
const [chosenRole, setChosenRole] = useState(false);
useEffect(() => {
roles.find((role) => {
if (role.id === status) {
setChosenRole(role);
return true;
}
return false;
});
}, []);
const handleClick = (data) => {
console.log(data);
setChosenRole(data);
};
return (
<View style={{ marginTop: 30 }}>
{roles.map((role) => {
return (
<View>
<RadioButton
label={role.name}
selected={role.name === chosenRole.name}
onPress={() => handleClick(role)}
/>
</View>
);
})}
</View>
);
}

create variable dynamically in react-native component

i need to create a variable in a react-native component, which i want to use several times...each instance of this component needs to have a different variable name to reference to.
<View ref={view => { shapeView = view; }}
onLayout={({ nativeEvent }) => {
shapeView.measure( (x, y, width, height, pageX, pageY) => {
console.log('- - - DEBUG: width:' + width + ', pageX:'+ pageX + ', pageY:' + pageY);
let shapePickerPosition = {w: width, x: pageX, y: pageY};
setShapeCoords(shapePickerPosition);
})
}}>
as i said, i want to use this code inside a component, and this component several times, and if i don't change die variable: "shapeView" i end up with just the coordinates from the last instance of that component..
here's the whole component:
import React, {useState, useEffect} from 'react';
import {StyleSheet, View, Text, Modal, TouchableOpacity, Pressable, FlatList} from 'react-native';
import { useTheme} from '#react-navigation/native';
// ------------------PickerRow-----------------------------------------------------------------------
function CustomPickerRow(props) {
const { colors } = useTheme(); // works
const theme = useTheme();
const [selectedItem, setSelectedItem] = useState('choose');
const [coordinates, setCoordinates] = useState();
const setItem = (value) => {
// set parent state
props.action(value)
}
return (
<View
ref = { view => { shapeView = view; } }
onLayout={({ nativeEvent }) => {
shapeView.measure( (x, y, width, height, pageX, pageY) => {
console.log('height:', height);
console.log('width:', width);
console.log('x:', pageX);
console.log('y:', pageY);
let coords = {w: width, x: pageX, y: pageY};
setCoordinates(coords);
})
}}
style = {{
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
height: 25,
paddingLeft: 5,
marginBottom: 3,
backgroundColor: colors.frameBackground,
borderColor: colors.borderColor,
borderWidth: 1,
borderRadius: 5}}>
<View style = {styles.icon} >
<Text style = {styles.text}>{props.icon}</Text>
</View>
<View style = {styles.description} >
<Text style = {{fontSize: 11, fontWeight: 'bold', color: colors.text, textAlign: 'left', marginLeft: 5,}}>{props.title}</Text>
</View>
<MyPicker data={props.data} action={setItem} position={coordinates}/>
</View>
);
}
// ------------------MyPicker-----------------------------------------------------------------------
function MyPicker(props) {
const { colors } = useTheme(); // works
const theme = useTheme();
const [isVisible, setIsVisible] = useState(false);
const [selectedItem, setSelectedItem] = useState(props.data[0].key)
const [coordinates, setCoordinates] = useState({w: 180, x: 0, y: 0});
useEffect(() => {
if (props.position) {
setCoordinates(props.position);
}
})
const setItem = item => {
// set parent state
props.action(item.value);
setIsVisible(false);
console.log("chosen value = " + item.key);
setSelectedItem(item.key);
}
const showPicker = () => {
setIsVisible(true);
}
const renderItem = ({item}) => {
return <View>
<Pressable onPress={() => setItem(item)}>
<Text style={{color: colors.text, fontSize: 17, alignSelf: 'center', paddingTop: 3}}>
{item.key}
</Text>
</Pressable>
</View>
}
return (
<View style={{flex:5, backgroundColor: 'transparent'}}>
<TouchableOpacity onPress={showPicker}>
<Text style={{color: colors.textSubtitleColor, fontSize: 11, alignSelf: 'flex-end', paddingRight: 10}}>
{selectedItem}
</Text>
</TouchableOpacity>
<Modal animationType="fade"
transparent={true}
visible={isVisible}
style={styles.testPicker}
onRequestClose={() => {
console.log('Modal has been closed.');
}}
>
<View style={{ backgroundColor: colors.frameBackground,
borderColor: colors.borderColor,
borderWidth: 1,
borderRadius: 5,
position: 'absolute',
width: 180,
height: 200,
left: coordinates.x, //100,
top: coordinates.y //160
}}>
<FlatList
data={props.data}
renderItem={renderItem}
/>
</View>
</Modal>
</View>
);
}
const styles = StyleSheet.create({
testPicker: {
backgroundColor: 'gray',
position: 'absolute',
width: 112,
height: 200,
left: 100,
top: 160
},
icon: {
flex: 1,
backgroundColor: '#00529F',
marginRight: 0,
borderRadius: 5
},
description: {
flex: 2,
height: 17,
backgroundColor: 'transparent',
marginRight: 0,
borderRadius: 5
},
});
export default CustomPickerRow;
and i call that component like this:
<CustomPickerRow id='shapePicker' icon='2' title='Shape:' data={shapeItems} action={setShape} selectedItem={selectedShape} visible={modalVisible} />```
shapeView should be a ref like this:
const MyComponent = () => {
const shapeView = useRef();
return (
<View
ref={view => shapeView.current = view}
/* could also look like this: ref={shapeView} */
onLayout={({nativeEvent}) => {
shapeView.current.measure(...);
}
/>
)
}
It SHOULD NOT be like this:
let shapeView; // this is outside your component - it shouldn't be here
const MyComponent = () => {
return (
<View
ref={view => shapeView = view}
onLayout={({nativeEvent}) => {
shapeView.measure(...);
}
/>
)
}
In a class based component it could look like this:
class MyComponent extends React.Component {
constructor() {
this.shapeView = React.createRef();
}
render() {
return (
<View
ref={this.shapeView}
onLayout={({nativeEvent}) => {
this.shapeView.current.measure(...);
}
/>
)
}
}

React Native: Touchable Opacity element is clickable on iOS but not Android

I'm working on a React Native app with a typeahead component. The typeahead displays options that overlay other content on the route (see right image below). When a user clicks one of those options, an onPress listener runs a function:
This all works just fine on iOS. On Android though, the onPress event is never received. Even more strangely, when I try to click on an option lower in the list (like Boston, MA, USA), the onPress event is received by the card below the pressed option (Djerba).
Does anyone know what might cause this behavior? I'd be super grateful for any insights others can offer on this query.
Here's the code for the Explore view and the typeahead components.
Explore.js
import React from 'react'
import { connect } from 'react-redux'
import { Text, View, ScrollView, TouchableOpacity } from 'react-native'
import { gradients, sizing } from '../../style'
import { LinearGradient } from 'expo-linear-gradient'
import { MountainHero } from '../Heros'
import { CardRow } from '../Card'
import Loading from '../Loading'
import { setExploreSearch, onExploreTypeaheadClick } from '../../actions/locations'
import { Typeahead } from '../Typeahead'
const styles = {
container: {
flex: 1,
flexDirection: 'column',
},
scrollView: {
paddingBottom: sizing.margin,
},
loadingContainer: {
position: 'absolute',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
zIndex: 100,
elevation: 100,
top: 53,
width: '100%',
},
typeahead: {
margin: sizing.margin,
marginBottom: 0,
width: sizing.screen.width - (2*sizing.margin),
zIndex: 100,
elevation: 100,
}
}
const Explore = props => {
const { authenticated: a, spotlight, loading } = props;
let r = (a.recommendedLocations || []);
if (!r || !spotlight) return null;
// remove spotlight locations from the recommended locations
const ids = spotlight.map(i => i.guid);
const recommended = r.filter(i => ids.indexOf(i.guid) == -1);
return (
<LinearGradient style={styles.container} colors={gradients.teal}>
<ScrollView contentContainerStyle={styles.scrollView}>
{loading && (
<View style={styles.loadingContainer}>
<Loading />
</View>
)}
<MountainHero text='Explore' />
<Typeahead
style={styles.typeahead}
placeholder='Search Cities'
value={props.exploreSearch}
onChange={props.setExploreSearch}
vals={props.exploreTypeahead}
valKey={'place_id'}
onTypeaheadClick={props.onExploreTypeaheadClick}
/>
<CardRow
text='Explore Places'
cards={recommended}
type='location' />
<CardRow
text='In the Spotlight'
cards={spotlight}
type='location' />
</ScrollView>
</LinearGradient>
)
}
const mapStateToProps = state => ({
authenticated: state.users.authenticated,
spotlight: state.locations.spotlight,
exploreSearch: state.locations.exploreSearch,
exploreTypeahead: state.locations.exploreTypeahead,
loading: state.locations.loading,
})
const mapDispatchToProps = dispatch => ({
setExploreSearch: s => dispatch(setExploreSearch(s)),
onExploreTypeaheadClick: val => dispatch(onExploreTypeaheadClick(val)),
})
export default connect(mapStateToProps, mapDispatchToProps)(Explore)
Typeahead.js
import React from 'react'
import { Text, View, TouchableOpacity } from 'react-native'
import { sizing, GradientInput } from '../style'
const styles = {
container: {
position: 'absolute',
zIndex: 100,
elevation: 100,
height: 400,
width: '100%',
},
input: {
width: '100%',
borderRadius: 0,
},
typeaheadContainer: {
position: 'absolute',
zIndex: 100,
elevation: 100,
top: 55,
width: '100%',
},
typeaheadRow: {
padding: 10,
paddingTop: 12,
paddingBottom: 12,
borderWidth: 1,
borderColor: '#eeeeee',
backgroundColor: '#ffffff',
marginBottom: -1,
},
typeaheadRowText: {
fontSize: 15,
fontFamily: 'open-sans',
lineHeight: 20,
backgroundColor: '#ffffff',
},
}
export const Typeahead = props => {
return (
<View style={[props.container, props.style]}>
<GradientInput style={styles.input}
placeholder={props.placeholder}
value={props.value}
onChange={props.onChange} />
<TypeaheadList vals={props.vals}
valKey={props.valKey}
onTypeaheadClick={props.onTypeaheadClick} />
</View>
)
}
export const TypeaheadList = props => {
if (!props.vals) return null;
return (
<View style={styles.typeaheadContainer}>
{props.vals.map(i => {
let text = i.text;
if (text.length > 31) text = text.substring(0,31) + '...';
return (
<TouchableOpacity activeOpacity={0.5} key={i[props.valKey]}
style={styles.typeaheadRow}
onPress={() => props.onTypeaheadClick(i[props.valKey])}>
<Text numberOfLines={1} style={styles.typeaheadRowText}>{text}</Text>
</TouchableOpacity>
)
})}
</View>
)
}
export default Typeahead
Try to move Typeahead component below all CardRow components and set position:absolute for Typeahead. Probably on android - the latest view shadow all views before (I am not sure, but I think you have to try it for next discovering issue).
You should also remove position: absolute from all but one component. Working code:
Explore.js
import React from 'react'
import { connect } from 'react-redux'
import { Text, View, ScrollView, TouchableOpacity } from 'react-native'
import { gradients, sizing } from '../../style'
import { LinearGradient } from 'expo-linear-gradient'
import { MountainHero } from '../Heros'
import { CardRow } from '../Card'
import Loading from '../Loading'
import { setExploreSearch, onExploreTypeaheadClick } from '../../actions/locations'
import { Typeahead } from '../Typeahead'
const styles = {
container: {
flex: 1,
flexDirection: 'column',
},
scrollView: {
paddingBottom: sizing.margin,
},
loadingContainer: {
position: 'absolute',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
zIndex: 1,
elevation: 1,
top: 53,
width: '100%',
},
topCardRow: {
paddingTop: sizing.margin + sizing.gradientInput.height,
},
typeahead: {
margin: sizing.margin,
marginBottom: 0,
width: sizing.screen.width - (2*sizing.margin),
zIndex: 1,
elevation: 1,
position: 'absolute',
top: sizing.mountainHero.height,
left: 0,
}
}
const Explore = props => {
const { authenticated: a, spotlight, loading } = props;
let r = (a.recommendedLocations || []);
if (!r || !spotlight) return null;
// remove spotlight locations from the recommended locations
const ids = spotlight.map(i => i.guid);
const recommended = r.filter(i => ids.indexOf(i.guid) == -1);
return (
<LinearGradient style={styles.container} colors={gradients.teal}>
<ScrollView contentContainerStyle={styles.scrollView}>
{loading && (
<View style={styles.loadingContainer}>
<Loading />
</View>
)}
<MountainHero text='Explore' />
<CardRow
style={styles.topCardRow}
text='Explore Places'
cards={recommended}
type='location' />
<CardRow
text='In the Spotlight'
cards={spotlight}
type='location' />
<Typeahead
style={styles.typeahead}
placeholder='Search Cities'
value={props.exploreSearch}
onChange={props.setExploreSearch}
vals={props.exploreTypeahead}
valKey={'place_id'}
onTypeaheadClick={props.onExploreTypeaheadClick}
/>
</ScrollView>
</LinearGradient>
)
}
const mapStateToProps = state => ({
authenticated: state.users.authenticated,
spotlight: state.locations.spotlight,
exploreSearch: state.locations.exploreSearch,
exploreTypeahead: state.locations.exploreTypeahead,
loading: state.locations.loading,
})
const mapDispatchToProps = dispatch => ({
setExploreSearch: s => dispatch(setExploreSearch(s)),
onExploreTypeaheadClick: val => dispatch(onExploreTypeaheadClick(val)),
})
export default connect(mapStateToProps, mapDispatchToProps)(Explore)
Typeahead.js
import React from 'react'
import { Text, View, TouchableOpacity } from 'react-native'
import { sizing, GradientInput } from '../style'
const styles = {
container: {
zIndex: 1,
elevation: 1,
height: 400,
width: '100%',
},
input: {
width: '100%',
borderRadius: 0,
},
typeaheadContainer: {
zIndex: 1,
elevation: 1,
top: 0,
width: '100%',
},
typeaheadRow: {
padding: 10,
paddingTop: 12,
paddingBottom: 12,
borderWidth: 1,
borderColor: '#eeeeee',
backgroundColor: '#ffffff',
marginBottom: -1,
zIndex: 1,
elevation: 1,
},
typeaheadRowText: {
fontSize: 15,
fontFamily: 'open-sans',
lineHeight: 20,
backgroundColor: '#ffffff',
},
}
export const Typeahead = props => {
return (
<View style={[props.container, props.style]}>
<GradientInput style={styles.input}
placeholder={props.placeholder}
value={props.value}
onChange={props.onChange} />
<TypeaheadList vals={props.vals}
valKey={props.valKey}
onTypeaheadClick={props.onTypeaheadClick} />
</View>
)
}
export const TypeaheadList = props => {
if (!props.vals) return null;
return (
<View style={styles.typeaheadContainer}>
{props.vals.map(i => {
let text = i.text;
if (text.length > 31) text = text.substring(0,31) + '...';
return (
<TouchableOpacity activeOpacity={0.5} key={i[props.valKey]}
style={styles.typeaheadRow}
onPress={() => props.onTypeaheadClick(i[props.valKey])}>
<Text numberOfLines={1} style={styles.typeaheadRowText}>{text}</Text>
</TouchableOpacity>
)
})}
</View>
)
}
export default Typeahead

Categories