React Native - cannot import image from path - javascript

I have the following basic react native code:
import React from 'react';
import {StyleSheet, View, Image} from 'react-native';
//images
import login_blueGirl from './assets/images/login_blueGirl.png';
const App = () => {
return (
<>
<View style={styles.container}>
<Image source={login_blueGirl}></Image>
</View>
</>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column'
}
});
export default App;
I'm getting a Cannot find module './assets/images/login_blueGirl.png'. When I type ./ VSCode give me however the autocomplete option:
Any clue on why this is happening?

That's not quite how you're supposed to be importing images, use require instead.
const App = () => {
return (
<View style={styles.container}>
<Image source={require("./assets/images/login_blueGirl.png")} />
</View>
);
};

You can specify the width and height of the image to display it, do this:
const App = () => {
return (
<View style={styles.container}>
<Image style={{ width: 100, height: 80 }} source={require("./assets/images/login_blueGirl.png")}></Image>
</View>
);
};
or
const styles = StyleSheet.create({
imgStyle: {
width: 50,
height: 50,
}
});
const App = () => {
return (
<View style={styles.container}>
<Image style={styles.imgStyle} source={require("./assets/images/login_blueGirl.png")}></Image>
</View>
);
};

To import a static file like a .png file, you can declare
const blueGirl = require("assets/images/login_blueGirl.png");
Then you can use it in an Image component
<Image style={styles.image} source={blueGirl} />
Also the image is used as a self closing tag you don't have to add another </Image> tag.
In order to fully understand how tags and syntax work always check out the official documentation
React Native API

Related

react native render error (view config getter callback for component 'div'?

I have a problem with react-native. I'm trying exercise to do todo app from how I watch on youtube lessons. Can't understand where is my fault? Youtuber instructor codes all of same, his code working but my code doesn't working.
This is app.js file:
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Task from './components/Task';
export default function App() {
return (
<View style={styles.container}>
<View style={styles.taskWrapper}>
<Text style={styles.sectionTitle}>Today Works</Text>
<View style={styles.items}>
<Task text={'Task1'} />
<Task text={'Task2'} />
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#E8EAED',
},
taskWrapper: {
paddingTop: 80,
paddingHorizontal: 20,
},
sectionTitle: {
fontSize: 24,
fontWeight: 'bold',
},
items: {
},
});
and this is /components/Task.js file;
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { TouchableOpacity } from 'react-native-web';
const Task = (props) => {
return(
<View style={styles.item}>
<View style={styles.itemLeft}>
<TouchableOpacity style={styles.square}></TouchableOpacity>
<Text style={styles.itemText}>{props.text}</Text>
</View>
<View style={styles.circular}></View>
</View>
)
}
const styles = StyleSheet.create ({
itemLeft: {
},
square: {
},
itemText: {
},
circular: {
},
});
export default Task;
That codes not working.
I got these errors in expo ;
You can see error here>
What is my fault?
You are importing TouchableOpacity from 'react-native-web' (maybe because of intellisense).
The compiler is then filling that with a <div> instead of a <View>.
Change it to just 'react-native'.

React Native: Passing useState() data to unrelated screens

Explanation: I am creating a fitness app, my fitness app has a component called WorkoutTimer that connects to the workout screen, and that screen is accessed via the HomeScreen. Inside the WorkoutTimer, I have an exerciseCount useState() that counts every time the timer does a complete loop (onto the next exercise). I have a different screen called StatsScreen which is accessed via the HomeScreen tab that I plan to display (and save) the number of exercises completed.
What I've done: I have quite literally spent all day researching around this, but it seems a bit harder with unrelated screens. I saw I might have to use useContext() but it seemed super difficult. I am fairly new to react native so I am trying my best haha! I have attached the code for each screen I think is needed, and attached a screenshot of my homeScreen tab so you can get a feel of how my application works.
WorkoutTimer.js
import React, { useState, useEffect, useRef } from "react";
import {
StyleSheet,
Text,
View,
TouchableOpacity,
Button,
Animated,
Image,
SafeAreaView,
} from "react-native";
import { CountdownCircleTimer } from "react-native-countdown-circle-timer";
import { Colors } from "../colors/Colors";
export default function WorkoutTimer() {
const [count, setCount] = useState(1);
const [exerciseCount, setExerciseCount] = useState(0);
const [workoutCount, setWorkoutCount] = useState(0);
const exercise = new Array(21);
exercise[1] = require("../assets/FR1.png");
exercise[2] = require("../assets/FR2.png");
exercise[3] = require("../assets/FR3.png");
exercise[4] = require("../assets/FR4.png");
exercise[5] = require("../assets/FR5.png");
exercise[6] = require("../assets/FR6.png");
exercise[7] = require("../assets/FR7.png");
exercise[8] = require("../assets/FR8.png");
exercise[9] = require("../assets/S1.png");
exercise[10] = require("../assets/S2.png");
exercise[11] = require("../assets/S3.png");
exercise[12] = require("../assets/S4.png");
exercise[13] = require("../assets/S5.png");
exercise[14] = require("../assets/S6.png");
exercise[15] = require("../assets/S7.png");
exercise[16] = require("../assets/S8.png");
exercise[17] = require("../assets/S9.png");
exercise[18] = require("../assets/S10.png");
exercise[19] = require("../assets/S11.png");
exercise[20] = require("../assets/S12.png");
exercise[21] = require("../assets/S13.png");
return (
<View style={styles.container}>
<View style={styles.timerCont}>
<CountdownCircleTimer
isPlaying
duration={45}
size={240}
colors={"#7B4FFF"}
onComplete={() => {
setCount((prevState) => prevState + 1);
setExerciseCount((prevState) => prevState + 1);
if (count == 21) {
return [false, 0];
}
return [(true, 1000)]; // repeat animation for one second
}}
>
{({ remainingTime, animatedColor }) => (
<View>
<Image
source={exercise[count]}
style={{
width: 150,
height: 150,
}}
/>
<View style={styles.timeOutside}>
<Animated.Text
style={{
color: animatedColor,
fontSize: 18,
position: "absolute",
marginTop: 67,
marginLeft: 35,
}}
>
{remainingTime}
</Animated.Text>
<Text style={styles.value}>seconds</Text>
</View>
</View>
)}
</CountdownCircleTimer>
</View>
</View>
);
}
const styles = StyleSheet.create({})
WorkoutScreen.js
import React, { useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import WorkoutTimer from "../components/WorkoutTimer";
export default function WorkoutScreen() {
return (
<View style={styles.container}>
<WorkoutTimer />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
});
HomeScreen.js
import React from "react";
import { StyleSheet, Text, View, SafeAreaView, Button } from "react-native";
import { TouchableOpacity } from "react-native-gesture-handler";
import { AntDesign } from "#expo/vector-icons";
import { Colors } from "../colors/Colors";
export default function HomeScreen({ navigation }) {
return (
<SafeAreaView style={styles.container}>
<Text style={styles.pageRef}>SUMMARY</Text>
<Text style={styles.heading}>STRETCH & ROLL</Text>
<View style={styles.content}>
<TouchableOpacity
style={styles.timerDefault}
onPress={() => navigation.navigate("WorkoutScreen")}
>
<Button title="START WORKOUT" color={Colors.primary} />
</TouchableOpacity>
<TouchableOpacity
style={styles.statContainer}
onPress={() => navigation.navigate("StatsScreen")}
>
<AntDesign name="barschart" size={18} color={Colors.primary} />
<Text style={{ color: Colors.primary }}>Statistics</Text>
<AntDesign name="book" size={18} color={Colors.primary} />
</TouchableOpacity>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({})
StatsScreen.js
import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { exerciseCount, workoutCount } from "../components/WorkoutTimer";
export default function StatsScreen() {
return (
<View style={styles.container}>
<Text display={exerciseCount} style={styles.exerciseText}>
{exerciseCount}
</Text>
<Text display={workoutCount} style={styles.workoutText}>
{workoutCount}
</Text>
</View>
);
}
const styles = StyleSheet.create({});
Home Screen Image
As far as I can tell, you're almost there! You're trying to get your 2 state
variables from the WorkoutTimer like this:
import { exerciseCount, workoutCount } from "../components/WorkoutTimer";
Unfortunatly this won't work :( . These two variables change throughout your
App's life-time and that kinda makes them "special".
In React, these kinds of variables need to be declared in a parent component
and passed along to all children, which are interested in them.
So in your current Setup you have a parent child relationship like:
HomeScreen -> WorkoutScreen -> WorkoutTimer.
If you move the variables to HomeScreen (HomeScreen.js)
export default function HomeScreen({ navigation }) {
const [exerciseCount, setExerciseCount] = useState(0);
const [workoutCount, setWorkoutCount] = useState(0);
you can then pass them along to WorkoutScreen or StatsScreen with something
like:
navigation.navigate("WorkoutScreen", { exerciseCount })
navigation.navigate("StatsScreen", { exerciseCount })
You'll probably have to read up on react-navigation's documentation for .navigate I'm not sure I remember this correctly.
In order to read the variable you can then:
export default function WorkoutScreen({ navigation }) {
const exerciseCount = navigation.getParam(exerciseCount);
return (
<View style={styles.container}>
<WorkoutTimer exerciseCount={exerciseCount} />
</View>
);
}
and finally show it in the WorkoutTimer:
export default function WorkoutTimer({ exerciseCount }) {
Of course that's just part of the solution, since you'll also have to pass
along a way to update your variables (setExerciseCount and setWorkoutCount).
I encourage you to read through the links I posted and try to get this to work.
After you've accumulated a few of these stateful variables, you might also want to look at Redux, but this is a bit much for now.
Your app looks cool, keep at it!
I ended up solving this problem with useContext if anyone is curious, it was hard to solve initially. But once I got my head around it, it wasn't too difficult to understand.
I created another file called exerciseContext with this code:
import React, { useState, createContext } from "react";
const ExerciseContext = createContext([{}, () => {}]);
const ExerciseProvider = (props) => {
const [state, setState] = useState(0);
//{ exerciseCount: 0, workoutCount: 0 }
return (
<ExerciseContext.Provider value={[state, setState]}>
{props.children}
</ExerciseContext.Provider>
);
};
export { ExerciseContext, ExerciseProvider };
and in App.js I used ExerciseProvider which allowed me to pass the data over the screens.
if (fontsLoaded) {
return (
<ExerciseProvider>
<NavigationContainer>
<MyTabs />
</NavigationContainer>
</ExerciseProvider>
);
} else {
return (
<AppLoading startAsync={getFonts} onFinish={() => setFontsLoaded(true)} />
);
}
}
I could call it with:
import { ExerciseContext } from "../components/ExerciseContext";
and
const [exerciseCount, setExerciseCount] = useContext(ExerciseContext);
This meant I could change the state too! Boom, solved! If anyone needs an explanation, let me know!
I think you have to use Mobx or Redux for state management. That will be more productive for you instead built-in state.

Trying to display a video inside a modal in react native

I am trying to display a youtube video inside a modal in react native.
Video gets displayed in the normal view(I.e., without a modal window) ,but I am not display the same video when it’s inside a modal.
Things I have tried so far:
//screen1.js
const [isVisible, setVisible] = useState(false);
<Touchable
          onPress={() => setVisible(true)}
          style={{
            minHeight: 200,
            backgroundColor: Colors.Black
          }}>
          <Text></Text>
        </Touchable>
<Modal isVisible={isVisible} onBackdropPress={() => setVisible(false)}>
        <View style={{ maxHeight: 400, backgroundColor: 'white' }}>
          <WebView
            javaScriptEnabled={true}
            source={{
              uri: 'https://www.youtube.com/embed/RJa4kG1N3d0'
            }}
          />
        </View>
  </Modal>
PS : I have used modal from ‘'react-native-modal';
import React, { useState } from 'react';
import {
Text,
View,
StyleSheet,
TouchableOpacity,
Modal,
WebView,
} from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
const App = () => {
const [isVisible, setVisible] = useState(false);
return (
<View style={styles.container}>
<TouchableOpacity
onPress={() => setVisible(true)}
style={{
height: 50,
backgroundColor: 'yellow',
}}>
<Text>Click me</Text>
</TouchableOpacity>
<Modal
style={{
}}
animationType="slide"
transparent={false}
visible={isVisible}
onRequestClose={() => {
alert('Modal has been closed.');
}}>
<View style={{
flex: 1,
backgroundColor: 'orange',
borderWidth: 1,
borderColor: 'orange',
marginTop: 22 }}>
<WebView
javaScriptEnabled={true}
style={{flex:1, borderColor:'red', borderWidth:1, height:400, width:400}}
source={{
uri: 'https://www.youtube.com/embed/RJa4kG1N3d0'
}}
/>
<TouchableOpacity onPress={() => setVisible(false)}>
<Text>Hide Modal</Text>
</TouchableOpacity>
</View>
</Modal>
</View>
);
};
export default App;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
});
Follow this snack : https://snack.expo.io/#prashen/modal-video
Use reactnative module 'react-modal-video'. After install module usr this line of code
channelname will be youtube
isOpen operate by using state
VideoId : this you will get from the link which you have used ie 'RJa4kG1N3d0' in your link.

calling a function within a text tag

I think I am getting something wrong, I keep getting an error of 'this.deliveryFareEstimate() is undefined'
I am trying to sum up values gotten from a prop, but its not working as planned, and I think maybe doing it wrong tho. I am roughly new to programming generally.
Below is a sample code I am using to achieve it.
import React, { Component } from "react";
import { View, Text, StyleSheet, Image, TouchableOpacity, SafeAreaView, StatusBar } from "react-native";
import { Ionicons } from "#expo/vector-icons";
import RNSlidingButton, { SlideDirection } from "../../components/RNSlidingButton";
import { Block } from "../../components";
const PerKm = 55;
const PerKg = 35;
export default class ConfirmBooking extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const { handleBackPress, estimatedWeight, deliveryDuration } = this.props;
FareEstimate = () => {
const totalDistanceCost = PerKm * deliveryDuration;
const totalParcelWeight = PerKg * estimatedWeight;
const estimatedFare = totalParcelWeight + totalDistanceCost;
return estimatedFare;
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.container}>
{/* Delivery Details */}
<View style={styles.header}>
<TouchableOpacity
onPress={handleBackPress}
style={styles.navBarButton}
>
<Ionicons name="md-arrow-back" size={23} color="#FFF" />
</TouchableOpacity>
<Text style={styles.headerText}> Details</Text>
</View>
{/* content holder */}
<View style={styles.content}>
<Block style={styles.generalBlock}>
<Text style={styles.generalBlockHeaderText}>
ETA from Pick up
</Text>
<Text style={styles.generalBlockText}>
{deliveryDuration} Mins
</Text>
</Block>
<Block style={styles.generalBlock}>
<Text style={styles.generalBlockHeaderText}>
Estimated Parcel Weight
</Text>
<Text style={styles.generalBlockText}>{estimatedWeight} Kg</Text>
</Block>
<View style={styles.fareAndConfirm}>
<Text style={styles.fareAndConfirmHeaderText}>Fare</Text>
<Text style={styles.fareAndConfirmText}>
${this.FareEstimate()}
</Text>
</View>
</View>
</View>
</SafeAreaView>
);
}
}
FareEstimate is not properly defined. Always use const or let to define a local variable.
const FareEstimate = () => {
const totalDistanceCost = PerKm * deliveryDuration;
const totalParcelWeight = PerKg * estimatedWeight;
const estimatedFare = totalParcelWeight + totalDistanceCost;
return estimatedFare;
};
Since FareEstimate is defined locally inside render(), Call it without this
<Text style={styles.fareAndConfirmText}>${FareEstimate()}</Text>

how to handle Onpress events in react native snap carousel

I have a class and in that class I am displaying carousel components like this
sampleclass.js
.
.
.
render{
return (
<Image ..>
<Text>
text
</Text>
<Image ..>
<js file tag where carousel is defined />
</Image>
<Text>
text
</Text>
<Image ..>
<js file tag where carousel is defined />
</Image>
.
.
.
</Image>
);
}
function fname(params..){
I also need to access carousel ref here
}
and I have another class where I have defined the carousel
carouselclass.js
import React, { PureComponent } from 'react';
import { Dimensions, StyleSheet, View } from 'react-native';
import Carousel from 'react-native-snap-carousel';
export default class ExampleCarousel extends PureComponent {
state = {
data: [{}, {}, {}, {}, {}, {}]
}
renderItem = () => (
<View style={styles.tile} />
);
render () {
return (
<View style={styles.container}>
<Carousel
data={this.state.data}
renderItem={this.renderItem}
itemWidth={Dimensions.get('window').width * 0.85}
sliderWidth={Dimensions.get('window').width}
containerCustomStyle={styles.carousel}
slideStyle={{ flex: 1 }}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
height: 300
},
carousel: {
flex: 1,
backgroundColor: 'red'
},
tile: {
flex: 1,
width: Dimensions.get('window').width * 0.85,
backgroundColor: 'yellow'
}
});
I have to handle the onPress event of the carousel swipe components in the function of sampleclass.js
How can I do this I know how to handle onPress events on react native but couldnt do this with react-native-snap-carousel since I am using it for the first time I have read examples given in the docs but couldnt find something related to this
If you want to handle single Carousel item's onPress prop, you need to add that to your render item.
Example
// change this
renderItem = () => (
<View style={styles.tile} />
);
// to this
_onPressCarousel = () => {
// here handle carousel press
}
renderItem = () => (
<TouchableOpacity onPress={this._onPressCarousel} style={styles.tile}>
<Image
style={styles.button}
source={require('./myButton.png')}
/>
</TouchableOpacity>
);
<Carousel
...
renderItem={(carousel, parallaxProps) =>
this._renderItem(carousel, parallaxProps)
}
...
/>
_renderItem(carousel, parallaxProps) {
const { item } = carousel;
return (
<TouchableOpacity
onPress={() => {
this._handlePress(item._id);
}}
>
...

Categories