React Native - Invalid prop source passed to Image - reactjs

I am completely new to react native dev, and I am trying to display and <Image>. I keep getting this error:
Warning: Failed prop type: Invalid prop source supplied to Image`
Here is what I have:
First, there is list of all images in project defined like this:
export const IMAGES = {
ScreenStart1: require('../../assets/img/app/startScreen/start1.jpg'),
}
This is the view which calls the image component:
import {IMAGES} from '../../shared/listOfImages'
import FullScreenImage from '../../components/fullScreenImage'
export default class StartScreen extends React.Component {
render (): React$Element<*> {
let src = IMAGES.ScreenStart1;
return (
<View style={{flex: 1}}>
<FullScreenImage src="{src}"/>
</View>
);
}
}
Finally the FullScreenImage component:
//this displays image in full screen
export default class FullScreenImage extends Component {
render (): React$Element<*> {
let src = this.props.src;
return (
<Image source={src} style={fullScreenImageStyle.container} resizeMode='cover'>
</Image>
);
}
}
Please can someone help me out?

I think your issue is <FullScreenImage src="{src}"/>, this literally passes down a string '{src}', if you want to inject a variable into a string you have to do this:
<FullScreenImage src={`${src}`}/>
But, is there a reason why you're not just doing <FullScreenImage src={src}/>?

Related

Navigation inside class component not working

While using class component I cannot use navigation its telling invalid hooks . How can I use navigation inside class component?
this is what i am trying to acheive , navigation option inside class component. actually i a m newbie .Can anyone help me?
import React, { Component } from 'react';
import { Text ,View ,TouchableOpacity } from 'react-native';
import { useNavigation } from '#react-navigation/native';
class Mpin extends Component {
const navigation= useNavigation();
render() {
return (
<Text>....</Text>
<TouchableOpacity onPress={()=>navigation.navigate('LoginPage')}>
<Text>SetMPIN</Text>
</TouchableOpacity>
);
}
}
export default Mpin;
You cannot use hooks inside class component. Inside class component you can directly access navigation object from props.
this.props.navigation.navigate('LoginPage')
Actually I can understand what you are trying to say. I came through this same kind of mistakes when I first started.
Use the below functional component inside of your class component like shown . By doing so you can access navigation inside class component.
import React, { Component } from 'react';
import { Text ,View ,TouchableOpacity } from 'react-native';
import { useNavigation } from '#react-navigation/native';
function ForgotMpin() {
const navigation = useNavigation();
return (
<View>
<TouchableOpacity
style={...}
onPress={() => navigation.navigate("ForgotPin")}
>
<Text>... </Text>
</TouchableOpacity>
</View>
);
}
class Mpin extends Component {
render() {
return (
<Text>....</Text>
<ForgotMpin screenName="forgotMpin" />
);
}
}
export default Mpin;
you can use vanilla js in those cases, the following code helps you redirect or navigate to other paths:
window.locate.replace('/pathname')
if you want to use Navigate or useNavigate you will have to convert to function component and not a class component

Getting an error while trying the context API in React JS. I am using context API with classes in ReactJS

I am trying the context API of React in my code. I tried the following code and getting the error
ReferenceError: Cannot access 'MyContextApi' before initialization
Context.api.parent.js:
import ContextChildOne from "./Context.api.childone";
import ContextChildTwo from "./Context.api.childtwo";
export const MyContextApi = React.createContext({});
class ContextParent extends React.Component {
render() {
return (
<div>
<p>context api parent tag</p>
<MyContextApi.Provider value={{ concept: "Context API" }}>
<ContextChildOne>
<ContextChildTwo />
</ContextChildOne>
</MyContextApi.Provider>
</div>
);
}
}
export default ContextParent;
I am consuming the above context API in the below file
Context.api.childtwo.js:
import { MyContextApi } from "./Context.api.parent";
class ContextChildTwo extends React.Component {
// static contextType = MyContextApi;
render() {
// let concept = this.context;
return (
<div>
<p>Child two of context</p>
<p>
THIS IS THE EXAMPLE OF CONTEXT API TO AVOID PROPS DRILLDOWN.
THIS CONCEPT <span>{this.context.concept}</span>
</p>
</div>
);
}
}
ContextChildTwo.contextType = MyContextApi;
export default ContextChildTwo;
I tried keeping export const MyContextApi = React.createContext({}); in other file and import it but it is of no use, i am getting the same error.
Pls, help me to solve this error ReferenceError: Cannot access 'MyContextApi' before initialization
I moved the code export const MyContextApi = React.createContext({}); to another file and imported it both in the parent and child components. Then, my code worked correctly without error.
Prior I tried importing only in the parent component and it didn't worked. Now, it is working.

GetElementById equivalent in React Native

I am working on creating a module for React-Native.
The module needs to highlight or point out certain elements on the screen based on configuration stored in a DB.
In Android, our database would consist of view ids and our code would highlight those view ids.
In HTML, the element Ids would be sufficient.
How do I define unique identifiers in React native.
These would be stored in a database and then highlighted in real-time. So the module would need to access the x, y, width and height of the elements in runtime
In HTML, I would use getElementbyId() and proceed to get its attributes. What would be the equivalent in React Native.
This works -
this.userNameRef.measure((width,height,fx,fy,px,py)=>{
console.log(fx)
console.log(fy)
})
If userNameRef is received as a string parameter, how can I get this data
First of all, have in your mind, the selection within React Native is different the web.
You don't select the element directly, you must take the reference through the prop of element.
All elements in React Native has a prop called ref, you will able to have access all informations about that component, you may call the methods and get properties values.
Example using class component:
class MyComponent extends React.Component {
onEndLoadImage = () => {
console.log(this.flatlist.current); // here have all methods and properties of Image
}
render() {
return (
<Image
ref={element => this.flatlist = element}
onLoadEnd={onEndLoadImage}
...
/>
);
}
}
Example using functional components with hooks:
function MyComponent {
const imageRef = useRef(null);
const onEndLoadImage = () => {
console.log(imageRef.current); // here have all methods and properties of Image
}
return (
<Image
ref={imageRef}
onLoadEnd={onEndLoadImage}
...
/>
);
}
You can use onLayout props on the required View to get the view dimensions on the React Native side.
import React from "react";
import {Text, View, StyleSheet} from "react-native";
const GetLayout = (props) => {
const _getLayout = (evt) => {
const data = evt.nativeEvent;
alert(JSON.stringify(data));
}
return(
<View style={{flex: 1}}>
<View style={{flex: 1}} onLayout={_getLayout}>
<Text>I am the required View</Text>
</View>
</View>
)
}
export default GetLayout;
const styles = StyleSheet.create({
})

return from navigation in react native give me undefined in this.props.navigation.state.params.filePath

i need help :).
my project is 2 pages in react native, MainPage and SoundRecord.
my init screen is MainPage and when i press the button 'take sound'
i move to another component to record sound(i move with react native navigation).
when i come back i want to return the filePath(where it save the file..).
i want to insert it to the state.
when i do this in MainPage:
this.state{
filePath: this.props.navigation.state.params.filePath
}
it give error:
undefined is not an object(evaluating 'this.props.navigation.state.params.filePath')
and i understand this because i start my project with MainPage and i dont have the filePath from the SoundRecord page.
what can i do?
can i do check if this.props.navigation.state.params.filePath !== undefined?
how to do it? i try almost everything...
i put the relevant code:
MainPage:
import React, { Component } from 'react';
import { Platform, StyleSheet, Text, View, TouchableOpacity } from 'react-native';
import ImagePicker from 'react-native-image-picker';
import { RNS3 } from 'react-native-aws3';
import { aws } from './keys';
import SoundRecord from './SoundRecord'
export default class MainPage extends Component {
constructor(props){
super(props);
this.state={
file:'' ,
config:'',
filePath: '',
fileName: '',
tag:''
};
}
MoveToSoundRecordPage = () => {
this.props.navigation.navigate('SoundRecord');
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity onPress={this.MoveToSoundRecordPage}>
<Text>take sound</Text>
</TouchableOpacity>
{/* <SoundRecord takeSound={this.takeSound}/> */}
<Text>{this.state.fileName}</Text>
<TouchableOpacity onPress={this.UploadToAWS.bind(this)}>
<Text>Upload To Aws</Text>
</TouchableOpacity>
</View>
);
}
}
SoundRecord when i finish to record i send the filePath like this:
finishRecord = (filePath) => {
this.props.navigation.navigate('MainPage',{filePath});
}
thank!
If you want to update something on the previous page then you can do it in the following way.
Create a function in the MainPage that updates the state with the new filepath.
Pass the function as as a param.
Use the passed function in SoundRecord to update the state in the MainPage
MainPage
In your MainPage add the following
sendFilepath = (filePath) => {
this.setState({filePath})
}
Update the MoveToSoundRecordPage function to take the sendFilepath as a parameter:
MoveToSoundRecordPage = () => {
this.props.navigation.navigate('SoundRecord', { sendFilepath: this.sendFilepath });
}
SoundRecord
Then in the SoundRecord page you want to update the finishRecord so that it calls the function that you have passed.
finishRecord = (filePath) => {
this.props.navigation.state.params.sendFilepath(filePath)
this.props.navigation.goBack();
}
Snack
Here is a snack https://snack.expo.io/#andypandy/navigation-passing-function that shows passing a function called sendFilepath from Screen1 to Screen2. Then in Screen2 it then calls the function that was passed and this updates the state in Screen1.
Please try this. It may help you
Add this in MainPage screen:
componentWillMount() {
const filePath = this.props.navigation.getParam('filePath', '');
this.setState({ filePath:filePath })
}

Passing React Navigation to Child of Child Component

I'm dynamically building my "screen" with the use of child "row" and "button" components. I'm only using this method because I can't find a flex-flow property available for react-native.
So basically I'm mapping through an array of arrays to build each row, and within the row, mapping through each array to build each button. Because the onPress needs to be set in the button, I'm passing the URL for each
onPress{() => this.props.navigation.navigate({navigationURL})
as a prop, first to the row, and then to the button. The problem is I keep getting the error 'Cannot read property 'navigation' of undefined. I'm sure this is because only the actual "screens" within the navigator have access to the navigation props. I've also tried passing
navigation={this.props.navigation}
but had no success. I've looked through all of the documentation and can't seem to find anything helpful. Anyone else encountered a similar situation?
If you want to access the navigation object from a component which is not part of navigator, then wrap that component in withNavigation HOC. Within the wrapped component you can access navigation using this.props.navigation. Take a look at the official document
Sample
import { withNavigation } from 'react-navigation';
...
class CustomButton extends React.Component {
render() {
return <Button title="Back" onPress={() => {
this.props.navigation.goBack() }} />;
}
}
export default withNavigation(CustomButton);
Hope this will help!
Ahhh, silly mistake. I wasn't setting up Props in the constructor. Thank you Prasun Pal for the help! Here's my code if someone else has an issue.
import React, { Component } from 'react'
import { Image, Text, TouchableOpacity, View } from 'react-native'
import { withNavigation } from 'react-navigation'
class ButtonName extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<TouchableOpacity
onPress={() => this.props.navigation.navigate('PageName')}
>
</TouchableOpacity>
)
}
}
export default withNavigation(ButtonName);

Resources