I'm currently learning react-native and react-native-maps (using typescript ES6) and I'm having some issues rendering markers in that they just don't appear. I've attempted to separate my logic into components that make's sense to me but I'm wondering if this is the reason I can't get them to render.
What I have is the following:
Main Map Component
<MapView style={styles.map}
region={this.props.region}
showsUserLocation={true}
followsUserLocation={false}>
<View>
<SearchCircle />
<MarkerList />
<View>
<MapView>
SearchCircle
The SearchCircle works perfectly and the code contains:
import { Circle } from 'react-native-maps';
...
class SearchCircle extends React.Component<SearchProps> {
render() {
return (
<Circle center={this.props.user.location}
radius={this.props.map.searchRadius}
fillColor={'rgba(230,238,255,0.5)'}
strokeColor={'#1A66FF'}
strokeWidth={1} />
);
}
}
MarkerList - ISSUE
The MarkerList is the component that does not render correctly. It contains:
class MarkerList extends React.Component<MarkerListProps> {
// render our contacts
render() {
return (
<View>
{this.props.markerlist[0] != undefined && this.props.markerList.map((marker, index) => (
this.renderMarker( marker, index )
))}
</View>
);
}
renderMarker( marker: MarkerEntry, index: number ) {
return (
<View key={index}>
<Marker coordinate={marker.location} title={marker.title} />
<Text>{'Lat: ' + marker.location.latitude + ', Long: ' + marker.location.longitude}</Text>
</View>
);
}
}
The MarkerList component does call render() when the state updates (when I update the markers locations) BUT only the Text element renders/updates correctly. The Lat/Lng is displayed correctly on my screen however the Marker element does not appear at all. The markerlist property for the MarkerList component is a list of type MarkerEntry which contains the following:
interface MarkerEntry {
title: string
location: LatLng
}
No matter what I try, I cannot get any markers to render from this array. If I statically define markers then everything works just fine but with my property array list map they never render.
Static Example that works
class MarkerList extends React.Component<MarkerListProps> {
// render our contacts
render() {
let marker = {
id: 'Test',
location: {
latitude: -31.970097415447232,
longitude: 115.92362245895334
}
};
let markerArray: any[] = [];
markerArray.push( marker );
return (
<View>
{markerArray[0] != undefined && markerArray.map((c, index) => (
<Marker key={index} coordinate={c.location} title={c.id} />
))}
</View>
);
}
}
Is anyone able to assist. I can't understand what I'm doing wrong or if I'm missing something about how react-native should be structured for this to work.
Thanks in advance!
So I've managed to solve my problem and thought I'd leave my final solution here for anyone else that needs it. The issues were with how I was defining the MapView and also with how I was returning the map results.
Map Component
For the main map component I had to remove the child <View> entry I had defined.
Before
<MapView style={styles.map}
region={this.props.region}
showsUserLocation={true}
followsUserLocation={false}>
<View>**
<SearchCircle />
<MarkerList />
<View>
<MapView>
After
<MapView style={styles.map}
region={this.props.region}
showsUserLocation={true}
followsUserLocation={false}>
<SearchCircle />
<MarkerList />
<MapView>
MarkerList
The second part I had to change was the render function and it's syntax in the render function.
Before
class MarkerList extends React.Component<MarkerListProps> {
// render our contacts
render() {
return (
<View>
{this.props.markerlist[0] != undefined && this.props.markerList.map((marker, index) => (
this.renderMarker( marker, index )
))}
</View>
);
}
renderMarker( marker: MarkerEntry, index: number ) {
return (
<View key={index}>
<Marker coordinate={marker.location} title={marker.title} />
<Text>{'Lat: ' + marker.location.latitude + ', Long: ' + marker.location.longitude}</Text>
</View>
);
}
}
After
Note the additional return statements outside and inside the map call and the removal of the <View> element.
class MarkerList extends React.Component<MarkerListProps> {
// render our contacts
render() {
return this.props.markerList.map((marker, index) => {
return( this.renderMarker( marker, index ));
});
}
renderMarker( marker: MarkerEntry index: number) {
return (
<View key={index}>
<Marker coordinate={marker.location} title={marker.title} />
</View>
);
}
}
Related
I don't know what I did wrong in this function, I thought I had a return but I don't think it's being considered, and when I change the closing brackets or parenthesis it shows an error :/
Can someone help me?
function PopSheet() {
let popupRef = React.createRef()
const sheet =() => {
const onShowPopup =()=> {
popupRef.show()
}
const onClosePopup =()=> {
popupRef.close()
}
return (
<SafeAreaView style ={styles.container}>
<TouchableWithoutFeedback onPress={onShowPopup}>
</TouchableWithoutFeedback>
<BottomPopup
title="Demo Popup"
ref ={(target) => popupRef =target}/>
onTouchOutside={onClosePopup}
</SafeAreaView>
);
}
};
You need to use the render function which is responsible for rendering or display the JSX element into your app.
render() {
return (
<SafeAreaView style={styles.container}>
<TouchableWithoutFeedback
onPress={onShowPopup}></TouchableWithoutFeedback>
<BottomPopup title="Demo Popup" ref={target => (popupRef = target)} />
onTouchOutside={onClosePopup}
</SafeAreaView>
);
}
I'm currently creating a small example of React Native. The issue I'm having is that when I tried to pass the image source from my LoginScreen component to ImageHolder component, the Node shows error below:
Loading dependency graph, done.
error: bundling failed: Error: src\ImageHolder.js:Invalid call at line 7: require({
imageSource: imageSource
})
at C:\Users\Kuro\vuichoi_ui\node_modules\metro\src\JSTransformer\worker.js:247:19
at Generator.next (<anonymous>)
at step (C:\Users\Kuro\vuichoi_ui\node_modules\metro\src\JSTransformer\worker.js:40:30)
at C:\Users\Kuro\vuichoi_ui\node_modules\metro\src\JSTransformer\worker.js:51:15
Here is my code:
LoginScreen.js render:
render() {
if (true) {
return (
<View>
<LoginText
imgSource="./img/account.png"
secureOption={false}
value={this.state.username}
placeholder="username"
onChangeText={username => this.setState(username)}
/>
</View>
)
}
}
LoginText.js:
const LoginText = ({imgSource, secureOption, placeholder, value, onChangeText}) => {
return (
<View style={styles.containerStyle}>
<ImageHolder imageSource={imgSource} />
<InputField placeholder={placeholder} secureOption={secureOption} value={value} onChangeText={onChangeText}/>
</View>
)
}
ImageHolder.js:
const ImageHolder = ({imageSource}) => {
return (
<View style={styles.imgContainerStyle}>
<Image source={require(imageSource)}></Image>
</View>
)
}
The issue is in the path of Image. If all the component on the same path then you can the same thing.
The solutions is that you need to pass Image from LoginScreen.js
render() {
if (true) {
return (
<View>
<LoginText
imgSource={require('./img/account.png')}
secureOption={false}
value={this.state.username}
placeholder="username"
onChangeText={username => this.setState(username)}
/>
</View>
)
}
}
ImageHolder.js
const ImageHolder = ({imageSource}) => {
return (
<View style={styles.imgContainerStyle}>
<Image source={imageSource}></Image>
</View>
)
}
Replace the code above tow js and it will work for you.
The question is almost similar to this one :
touchableopacity onpress function undefined (is not a function) React Native
But the problem is, I am getting the error despite the fact that I have bind the function. Here is my TouchableOpacity component:
<TouchableOpacity style={styles.eachChannelViewStyle} onPress={() => this.setModalVisible(true)}>
{item.item.thumbnail ?
<Image style={styles.everyVideoChannelThumbnailStyle} source={{uri: item.item.thumbnail}} />
: <ActivityIndicator style= {styles.loadingButton} size="large" color="#0000ff" />}
<Text numberOfLines={2} style={styles.everyVideoChannelVideoNameStyle}>
{item.item.title}
</Text>
</TouchableOpacity>
And this is my setModalVisible function:
setModalVisible(visible) {
console.error(" I am in set modal section ")
this.setState({youtubeModalVisible: visible});
}
Also, I have bind the function in constructor as follows:
this.setModalVisible = this.setModalVisible.bind(this);
But, I am still getting same error that undefined is not a function. Any help regarding this error?
The render method and your custom method must be under the same scope. In code below I have demonstrated the same. I hope you will modify your code accordingly as I assume you got the gist :)
class Demo extends Component {
onButtonPress() {
console.log("click");
}
render() {
return (
<View>
<TouchableOpacity onPress={this.onButtonPress.bind(this)}>
<Text> Click Me </Text>
</TouchableOpacity >
<View>
);
}
}
Alternatively binding method in constructor will also work
class Demo extends Component {
constructor(props){
super(props);
this.onButtonPress= this.onButtonPress.bind(this);
}
onButtonPress() {
console.log("click");
}
render() {
return (
<View>
<TouchableOpacity onPress={this.onButtonPress()}>
<Text> Click Me </Text>
</TouchableOpacity >
<View>
);
}
}
I'm not sure if this will help but I write my functions this way and haven't encountered this problem.
If I were you I'd try binding the function in the place where you declare it.
setModalVisible = (visible) => {
this.setState({ youtubeModalVisible: visible });
}
If you do this, you don't have to bind in the constructor.
constructor(props) {
...
// Comment this out to see it will still bind.
// this.setModalVisible = this.setModalVisible.bind(this);
...
}
Lastly, if this function will only set the modal's state to visible, you might want to remove the argument and pass it this way.
<TouchableOpacity style={styles.eachChannelViewStyle} onPress={this.setModalVisible}>
...
</TouchableOpacity>
// Refactored function declaration would look like this
setModalVisible = () => {
this.setState({ youtubeModalVisible: true });
}
I want to pass the clicked searchItem's id from my component. My code is as follows.
const searchResultList = props => (
<View style={styles.container}>
<ScrollView keyboardShouldPersistTaps="always">
{props.itemList.map(item => (
<SearchResultListItem
key={item.id}
imageSource={item.workoutImage}
mainText={item.workoutName}
subText={item.length + " | " + item.difficulty}
onItemPressed={props.onItemPressed}
/>
))}
</ScrollView>
</View>
);
When, onItemPressed, i want to pass the item.id with the prop.onItemPressed. This is my screen.
<SearchResultList
itemList={this.props.searchedWorkouts}
onItemPressed={id => alert(item.id)} //this.onLoadWorkoutDetailView()}
/>
How can I achieve this? I want the clicked itemId to my main screen.
You need to make an addition function. Straightforward it will be like this:
...
onItemPressed={() => props.onItemPressed(item.id)}
...
But, it`s not a good solution from performance point of view.
The better way is to make a method and bind all items to this method.
class SearchResultList extends React.PureComponent {
constructor(props) {
super(props);
const {itemsList} = props;
this._onPressHandlers = {};
for (let {id} for itemsList) {
this._onPressHandlers[id] = this._onItemPress.bind(this, id);
}
}
_onItemPress(id) {
return this.props.onItemPressed(id);
}
render() {
return (
<View style={styles.container}>
<ScrollView keyboardShouldPersistTaps="always">
{props.itemList.map(item => (
<SearchResultListItem
key={item.id}
imageSource={item.workoutImage}
mainText={item.workoutName}
subText={item.length + " | " + item.difficulty}
onItemPressed={this._onPressHandlers[item.id]}
/>
))}
</ScrollView>
</View>
);
}
}
In this case the handlers will not be generated on each render of list and will not cause re-render of SearchResultListItem component.
Obviously, if you expect changes of the itemsList prop, you will need to rebind it on componendWillReceiveProps method.
I am trying to implement a collapsible box in react native.Its working fine for dummy data. But when i tried to list the data response from server i'm getting error.I'm using map method over the response for listing the details.But showing error evaluating this.state.details.map.Also i'm confused to where to place the map method.Below is the code that i've tried.I refer this doc for collapsible box.
Example
class DetailedView extends Component{
constructor(props){
super(props);
this.icons = {
'up' : require('../Images/Arrowhead.png'),
'down' : require('../Images/Arrowhead-Down.png')
};
this.state = {
title : props.title,
expanded : true,
animation : new Animated.Value()
};
}
toggle(){
let initialValue = this.state.expanded? this.state.maxHeight + this.state.minHeight : this.state.minHeight,
finalValue = this.state.expanded? this.state.minHeight : this.state.maxHeight + this.state.minHeight;
this.setState({
expanded : !this.state.expanded
});
this.state.animation.setValue(initialValue);
Animated.spring(
this.state.animation,
{
toValue: finalValue
}
).start();
}
_setMaxHeight(event){
this.setState({
maxHeight : event.nativeEvent.layout.height
});
}
_setMinHeight(event){
this.setState({
minHeight : event.nativeEvent.layout.height
});
}
state = {details: []};
componentWillMount(){
fetch('https://www.mywebsite.com' + this.props.navigation.state.params.id )
.then((response) => response.json())
.then((responseData) =>
this.setState({
details:responseData
})
);
}
render(){
let icon = this.icons['down'];
if(this.state.expanded){
icon = this.icons['up'];
}
return this.state.details.map(detail =>
<Animated.View
style={[styles.container,{height: this.state.animation}]}>
{detail.data.curriculum.map(curr =>
<View onLayout={this._setMinHeight.bind(this)}>
<Card>
<CardSection>
<View style={styles.thumbnailContainerStyle}>
<Text style={styles.userStyle}>
Hii
</Text>
</View>
<TouchableHighlight onPress={this.toggle.bind(this)}
underlayColor="#f1f1f1">
<Image style={styles.buttonImage} source={icon}></Image>
</TouchableHighlight>
</CardSection>
</Card>
</View>
<View style={styles.body} onLayout={this._setMaxHeight.bind(this)}>
{this.props.children}
<Card>
<CardSection>
<Text>{this.props.navigation.state.params.id}</Text>
</CardSection>
</Card>
</View>
)}
</Animated.View>
);
}
}
This is the screenshot for working code with dummy data
1. Solving the Error :
The API call you are making is asynchronous and once the API is called, the code continues to execute before getting the response from the API. The component tries to map through this.state.details before there are any details.
A solution here is that you need to set an ActicityIndicator/Loader initially when component is mounted and once you get the details/response from the API, the state changes and then you can map through this.state.details
Add empty details array to your initial state.
state = { details:[] }
Then put your return this.state.details.map(detail.... Inside an if condition like this
if(this.state.details.length > 0) {
<map here>
} else {
return <ActivityLoader />
}
2. Where to place the map methiod
You need to put it inside a function and call that function from within you render method.
showDetailsFunction() {
return this.state.details.map(detail =>
}
render() {
return(
{this.showDetailsFunction()}
)
}