How can I convert stateless function to class component in react native - javascript

I am new in react native, I have been looking for how to convert this function to a class component in react native. Please I need help to convert the code below to react component.
import React from 'react';
import { View, Image, ScrollView } from 'react-native';
import styles from './styles';
export default ({captures=[]}) => (
<ScrollView
horizontal={true}
style={[styles.bottomToolbar, styles.galleryContainer]}
>
{captures.map(({ uri }) => (
<View style={styles.galleryImageContainer} key={uri}>
<Image source={{ uri }} style={styles.galleryImage} />
</View>
))}
</ScrollView>
);

To turn this into a class component, just move the code into the class component's render method, and change references to props with references to this.props. For this component, no other changes are needed.
export default class Example extends React.Component {
render () {
const { captures = [] } = this.props;
return (
<ScrollView
horizontal={true}
style={[styles.bottomToolbar, styles.galleryContainer]}
>
{captures.map(({ uri }) => (
<View style={styles.galleryImageContainer} key={uri}>
<Image source={{ uri }} style={styles.galleryImage} />
</View>
))}
</ScrollView>
)
}
}

Related

Error in putting ImageView component within View component

When I'm putting ImageView component within View component, I am getting the error: Error: Text strings must be rendered within a component. I don't understand what is wrong over here. Below is the code snippet:
import React from 'react';
import { View, Image, ScrollView, TouchableOpacity, Modal, Text } from 'react-native';
import styles from './cameraStyles';
import ImageView from "react-native-image-viewing";
export default ({captures=[], lflagImage=false}) => {
const [flagImage, setflagImage] = React.useState(lflagImage);
return (
<ScrollView horizontal={true} style={[styles.bottomToolbar, styles.galleryContainer]}>
{captures.map(({ uri }) => (
<View style={styles.galleryImageContainer} key={uri}>
<TouchableOpacity onPress={()=> {setflagImage(prevData => !prevData)}}>
<Image source={{ uri }} style={styles.galleryImage}/>
</TouchableOpacity>
<ImageView
images={captures}
imageIndex={0}
visible={flagImage}
onRequestClose={() => setflagImage(prevData => !prevData)}
/>
</View>
))}
</ScrollView>
)
}
It looks like you have an extra set of braces within your TouchableOpacity's onPress event. It should be:
onPress={()=> setflagImage(prevData => !prevData)}
This could be causing the issue you are experiencing.
I also can't see what styles.galleryImage is, but make sure you are defining a height and width or else it won't display anyway.

ERROR: Touchable child must either be native or forward setNativeProps to a native component

I am currently doing ReactNative course from coursera and the course is 4 years old and i am facing this error: Touchable child must either be native or forward setNativeProps to a native component.
I've no idea what this is. It will be greatly helpful if someone will help me.Adding files details as well:
App.js
import React from 'react';
import Main from './components/MainComponent';
export default class App extends React.Component {
render() {
return (
<Main />
);
}
}
MainComponent.js
import React, { Component } from 'react';
import Menu from './MenuComponent';
import { DISHES } from '../shared/dishes';
import Dishdetail from './DishdetailComponent';
import { View } from 'react-native';
class Main extends Component {
constructor(props) {
super(props);
this.state = {
dishes: DISHES,
selectedDish: null,
};
}
onDishSelect(dishId) {
this.setState({selectedDish: dishId})
}
render() {
return (
<View style={{flex:1}}>
<Menu dishes={this.state.dishes} onPress={(dishId) => this.onDishSelect(dishId)} />
<Dishdetail dish={this.state.dishes.filter((dish) => dish.id === this.state.selectedDish)[0]} />
</View>
);
}
}
export default Main;
MenuComponent.js
import React from 'react';
import { View, FlatList } from 'react-native';
import { ListItem } from 'react-native-elements';
function Menu(props) {
const renderMenuItem = ({item, index}) => {
return (
<View>
<ListItem
key={index}
title={item.name}
subtitle={item.description}
hideChevron={true}
onPress={() => props.onPress(item.id)}
leftAvatar={{ source: require('./images/uthappizza.png')}}
/>
</View>
);
};
return (
<View>
<FlatList
data={props.dishes}
renderItem={renderMenuItem}
keyExtractor={item => item.id.toString()}
/>
</View>
);
}
export default Menu;
Dishdetailcomponent.js
import React from 'react';
import { Text, View } from 'react-native';
import { Card } from 'react-native-elements';
function Dishdetail(props) {
return(
<View >
<RenderDish dish={props.dish} />
</View>
);
}
function RenderDish(props) {
const dish = props.dish;
if (dish != null) {
return(
<View>
<Card
featuredTitle={dish.name}
image={require('./images/uthappizza.png')}>
<Text style={{margin: 10}}>
{dish.description}
</Text>
</Card>
</View>
);
}
else {
return(<View></View>);
}
}
export default Dishdetail;
Help will be appreciated!!
Thanks
I had same issue some days before. Quickfix for this issue.
import TouchableOpacity form 'react-native';
Add following in the MenuComponent.js
<ListItem
Component={TouchableOpacity}
key={item.id}
title={item.name}
subtitle={item.description}
hideChevron={true}
onPress={() => props.onPress(item.id)}
leftAvatar={{ source: require('./images/uthappizza.png')}}
/>
and run the program again. This will fix your problem.

How to use HoC with React Native

I have an listing app where users can add items for multiple categories, when they want to add new record, there are 3 related screens with this particular feature. All of those screens have <Header/> component, so i thought HoC would be nice here so that i can reuse it across 3 screens.
However, i could not accomplish it.
Here is what i tried so far:
This is my HoC class
import React, { Component } from 'react';
import { View, StyleSheet, Text, StatusBar } from 'react-native';
import Header from '../components/Header';
const NewAd = (WrappedComponent) => {
class NewAdHoc extends Component {
handleBackPress = () => {
this.props.navigation.navigate('Home');
StatusBar.setBarStyle('dark-content', true);
}
render() {
const {contentText, children} = this.props
return (
<View style={styles.container}>
<Header
headerText={'Yeni ilan ekle'}
onPress={this.handleBackPress}
/>
<View style={styles.contentContainer}>
<Text style={styles.contentHeader}>{contentText}</Text>
<WrappedComponent/>
</View>
</View>
);
}
}
return NewAdHoc;
}
this is my screen:
class NewAdScreen extends Component {
render() {
const Content = () => {
return (
<View style={styles.flatListContainer}>
<ListViewItem />
</View>
);
}
return (
NewAdHoc(Content)
)
}
}
after that i am getting error
TypeError: (0 , _NewAdHoc.NewAdHoc) is not a function(…)
and i have no idea how can i fix it because this is my first time using hocs on a react-native app. I have looked why this error is popping and they suggest import components in this way:
import {NewAdHoc} from '../hocs/NewAdHoc';
but even this is not solved it.
any help will be appreciated, thanks.
The main purpose of a HOC is to encapsulate and reuse stateful logic across components. Since you are just reusing some jsx and injecting nothing in WrappedComponent you should be using a regular component here:
const NewAd = ({ contentText, children }) => {
handleBackPress = () => {
this.props.navigation.navigate('Home');
StatusBar.setBarStyle('dark-content', true);
}
return (
<View style={styles.container}>
<Header
headerText={'Yeni ilan ekle'}
onPress={this.handleBackPress}
/>
<View style={styles.contentContainer}>
<Text style={styles.contentHeader}>{contentText}</Text>
{children}
</View>
</View>
);
}
And use it like this
return(
<>
<NewAd>
<Screen1 />
</NewAd>
<NewAd>
<Screen2 />
</NewAd>
<NewAd>
<Screen3 />
</NewAd>
</>
)

React-Native : ScrollView not showing the full content

I'm building an app with React-Native and for my Home Page im using the ScrollView but it doesn't show the full content. I have e header on the top so that may be blocking the full content or i don't know.
The code :
import React from "react";
import { View, StyleSheet, Text, ScrollView } from "react-native";
import Content from "../components/Content/content";
import Header from "../components/Header/header";
import Carousel1 from "../components/Carousel/index";
import Buttons from "../components/Buttons/buttons";
export default class HomeScreen extends React.Component {
static navigationOptions = ({ navigation }) => {
let drawerLabel = "Home";
return { drawerLabel };
};
render() {
return (
<View style={styles.container}>
<Header {...this.props} />
<ScrollView style={{flex:1}}>
<Carousel1 />
<Content />
<Buttons />
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#f9f9f9"
}
});
Any idea how to fix this?
Try it with react native Flatlist instead of ScrollView:
React-native Flatlist
Try using contentContainerStyle instead of style with ScrollView.
Since I don't have access to your Carousel1 , Content, and Buttons component to give you a certain answer, I suggest you try the following:
render() {
return (
<View style={styles.container}>
<Header {...this.props} />
<ScrollView contentContainerStyle={{ flexDirection:"column" }}>
<Carousel1 />
<Content />
<Buttons />
</ScrollView>
</View>
);
}
}
Report back with your results.
Remove style={{flex:1}} from ScrollView and see

Custom button Component in React Native is not accepting props

I made a custom Button(component) in react native to use it in the whole app with required parametric values(color,title,onPress funtion etc) but it's not accepting the values,I'm passing on calling
here's my button class
import React from 'react';
import {Button,Text} from 'react-native';
export const CustomButton = ({btnTitle, btnBgColor,btnPress}) =>
(
<Button
title={btnTitle}
style={
{
width:'200',
height:'40',
padding:10,
marginTop:20,
backgroundColor:'btnBgColor',
}}
onPress = {btnPress}>
</Button>
);
here I'm using it
export class Login extends Component<Props> {
render() {
return(
<View style={styles.containerStyle}>
<ImageBackground source={require ('./../../assets/images/bg.jpg')}
style={styles.bgStyle}/>
<View style={styles.loginAreaViewStyle}>
<Image />
<CustomInputField
inputPlaceholder={'Email'}
userChoice_TrF={false}
/>
<CustomInputField
inputPlaceholder={'Password'}
userChoice_TrF={true}
/>
<CustomButton
btnTitle={'Login'}
btnBgColor={'black'}
btnPress={this._LoginFunction()}/>
</View>
</View>
);
}
_LoginFunction()
{
return(alert('Login successful'))
}}
here's outn put
you can see my parametric values, color,widh,height etc made no effect on button
here i made some changes in your code.
import React from "react";
import {TouchableOpacity,Text} from 'react-native';
export const AppButton = ({btnTitle, btnBgColor, textColor, btnTextSize, btnPress, btnPadding})=>(
<TouchableOpacity style={{backgroundColor:btnBgColor }} onPress={btnPress}>
<Text style={{color:textColor, fontSize:btnTextSize, padding: btnPadding}}>
{btnTitle}
</Text>
</TouchableOpacity>
)
And use it like this, definitely it will solve your problem.
import {AppButton} from "../../components/AppButton";
<AppButton
btnBgColor={'#2abec7'}
btnPadding={10}
btnPress={this._LoginFunction}
btnTextSize={18}
btnTitle={'list'}
textColor={'#000'}
/>
and don't use () at
btnPress={this._LoginFunction()}
simply use it as
btnPress={this._LoginFunction}
The issue is because you have basically created a wrapper around the Button component from react-native
https://facebook.github.io/react-native/docs/button
If you look at the documentation for the button there are only 7 props that you can use
https://facebook.github.io/react-native/docs/button#props
onPress
title
accessibilityLabel
color
disabled
testID
hasTVPreferredFocus
There is no style prop. So what you are passing is just ignored.
What you need to do in your CustomButton is use one of the Touchables
https://facebook.github.io/react-native/docs/handling-touches#touchables
So you're component could become something like this (you may need to adjust the styling etc):
import React from 'react';
import {TouchableOpacity,Text} from 'react-native';
export const CustomButton = ({btnTitle, btnBgColor,btnPress}) =>
(
<TouchableOpacity
style={{
width:200,
height:40,
padding:10,
marginTop:20,
backgroundColor:{btnBgColor},
}}
onPress = {btnPress}>
<Text>{btnTitle}</Text>
</TouchableOpacity>
);
Also the values that you need to pass for the width and height need to be numbers.
Here is a snack with it working https://snack.expo.io/#andypandy/custom-button-example
Use arrow funtion like this
See the diffrence
export const CustomButton = ({btnTitle, textColor, textSize, btnBgColor, btnPress}) =>
({
<Button
title={btnTitle}
style={{
width:'200',
height:'40',
padding:10,
marginTop:20,
backgroundColor:{btnBgColor},
}}
onPress = {btnPress}>
</Button>
});
<CustomButton
btnTitle='login'
btnBgColor='black'
btnPress={this._LoginFunction()}
/>

Categories