How would I call a function from another component in react native? - javascript

How would I call a function from another component?
App.js
<Button onPress={movePopUpCard()}></Button>
<PopUpCard/>
PopUpCard.js
const movePopUpCard = () => {
//Code to update popUpCardX
}
<Animated.View style={[
{transform: [{scale: scale}, {translateX: popUpCardX}]},
{position: 'absolute'}
]}>
</Animated.View>

By using ref and forwardRef you can achieve this.
snack ex: https://snack.expo.io/#udayhunter/frisky-pretzels
App.js
import React,{useRef,useEffect} from 'react';
import { Text, View, StyleSheet } from 'react-native';
import PopUp from './PopUpCard'
const App =(props)=> {
const childRef = useRef(null)
return (
<View style={styles.container}>
<PopUp ref={childRef}/>
<Text
onPress = {()=>{
childRef.current.updateXvalue(10)
}}
>Press me</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
});
export default App
popUp.js
import React,{useState,useImperativeHandle,useEffect,forwardRef} from 'react'
import {View,Text,StyleSheet,Animated} from 'react-native'
const PopUp = (props,ref) => {
const [xValue, setXvalue] = useState(10)
const updateXvalue = (x)=>{
setXvalue(prev=> prev+x)
}
useImperativeHandle(ref, () => ({
updateXvalue
}));
return(
<Animated.View style = {[styles.mainView,{transform:[{translateX:xValue}]}]}>
</Animated.View>
)
}
const styles = StyleSheet.create({
mainView : {
height:100,
width:100,
backgroundColor:'red'
}
})
export default forwardRef(PopUp)

If you are using a functional component you have to use forwardRef to add reference to the component and useImperativeHandle to implement the method which you want to access through reference here is an example. Here I am calling bounce method which increases the scale of the component:
Snack: https://snack.expo.io/#ashwith00/adequate-salsa
Code:
App.js
export default function App() {
const boxRef = React.useRef();
return (
<View style={styles.container}>
<AnimatedBox ref={boxRef} />
<Button title="Bounce" onPress={() => boxRef.current.bounce()} />
</View>
);
}
AnimatedBox.js
import React, { forwardRef, useImperativeHandle, useRef } from 'react';
import { View, Animated } from 'react-native';
export default forwardRef((props, ref) => {
const scale = useRef(new Animated.Value(1)).current;
useImperativeHandle(
ref,
() => ({
bounce: () => {
Animated.timing(scale, {
toValue: 1.5,
duration: 300,
}).start(({ finished }) => {
if (finished) {
Animated.timing(scale, {
toValue: 1,
duration: 300,
}).start();
}
});
},
}),
[]
);
return (
<Animated.View
style={{
width: 100,
height: 100,
backgroundColor: 'red',
transform: [{scale}]
}}
/>
);
});

move the function movePopUpCard to app.js
and pass in app.js pass it in
<PopUpCard movePopUpCard={(params) => movePopUpCard(params)}/>
you can call the function from PopUpCard component by this.props.movePopUpCard(params)
you can also pass params if requrired

Related

TypeError: undefined is not an object (evaluating '_this.camera = _ref')

-App dev in React Native-
Hello,
I have a problem with Expo Camera. Here an error is referred when you want to take a picture.
"TypeError: undefined is not an object (evaluating '_this.camera = _ref')" / Scan.js.
If the app is freshly updated with Expo, everything works. But as soon as you continue programming and another error occurs, this error appears and doesn't go away until you refresh the app again.
I have tried a lot, but I need help here.
Scan.js
import React, { Component, useState, useEffect } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Image } from 'react-native';
import {launchCamera, launchImageLibrary} from 'react-native-image-picker';
import {Camera, Constants} from 'expo-camera';
import * as MediaLibrary from 'expo-media-library';
import * as Haptics from 'expo-haptics';
import Images from '../assets/icon/index'
const Scan = () => {
const [hasPermission, setHasPermission] = useState(null);
const [type, setType] = useState(Camera.Constants.Type.back);
const [status, requestPermission] = MediaLibrary.usePermissions();
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>;
}
takePicture = async () => {
if (this.camera) {
let photo = await this.camera.takePictureAsync();
Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium);
console.log(photo.uri);
MediaLibrary.saveToLibraryAsync(photo.uri);
}
};
return (
<View style={styles.container}>
<Camera style={styles.camera}
type={type}
ref={ref => {
this.camera = ref;
}}>
<View style={styles.buttonContainer}>
<TouchableOpacity
style={styles.button}
onPress={() => {
setType(
type === Camera.Constants.Type.back
? Camera.Constants.Type.front
: Camera.Constants.Type.back
);
}}
>
<Image source={Images.camera} style={styles.icon}></Image>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={takePicture}
>
<Text style={styles.text}>Take</Text>
</TouchableOpacity>
</View>
</Camera>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
camera: {
flex: 1,
},
buttonContainer: {
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'row',
margin: 20,
top: 0,
},
button: {
flex: 0.1,
alignSelf: 'flex-end',
alignItems: 'center',
},
text: {
fontSize: 18,
color: 'white',
},
icon : {
tintColor: 'white',
},
})
export default Scan; ```
Create a new camera reference and attach it to the Camera component.
import { useRef } from 'react';
...
const cameraRef = useRef<Camera>(null);
...
<Camera ref={cameraRef} ... />
In your takePicture function replace this.camera.takePictureAsync with cameraRef.current?.takePictureAsync
Error: Function components cannot have string refs. We recommend using useRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref.
This is because the guy who answered used TypeScript.
Simply replace
const cameraRef = useRef(null);
with
const cameraRef = useRef(null);

I cannot use "this" on a function

I am new to React Native. I want to create a simple counter button. I could not use "this", it gives error ('this' implicitly has type 'any' because it does not have a type annotation.). You can see my TabTwoScreen.tsx TypeScript code below. I searched other questions but i could not find what to do. Why this is not working and how can I correct it. Waiting for helps. Thanks a lot.
import * as React from 'react';
import { StyleSheet, Button, Alert } from 'react-native';
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
export default function TabTwoScreen() {
const state={
counter: 0,
}
const but1 = () => {
this.setState({counter : this.state.counter + 1});
};
return (
<View style={styles.container}>
<Text style={styles.title}>Counter:{state.counter}</Text>
<Button
title="Increment"
onPress={but1}
accessibilityLabel="increment"
color="blue"
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 20,
fontWeight: 'bold',
},
separator: {
marginVertical: 30,
height: 1,
width: '80%',
},
});
Error Message
App Output:
import React, { useState } from 'react';
import { StyleSheet, Button, Alert, Text, View } from 'react-native';
export default function TabTwoScreen() {
// ๐Ÿ‘‡ You are using functional components so use the useState hook.
const [counter, setCounter] = useState(0);
const but1 = () => {
// ๐Ÿ‘‡then you can increase the counter like below
setCounter(counter + 1);
};
return (
<View style={styles.container}>
<Text style={styles.title}>Counter:{counter}</Text>
<Button
title="Increment"
onPress={but1}
accessibilityLabel="increment"
color="blue"
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 20,
fontWeight: 'bold',
},
});
And if you want to use Class based component then here is the implementation:
import React, { useState, Component } from 'react';
import { StyleSheet, Button, Alert, Text, View } from 'react-native';
export default class TabTwoScreen extends Component {
constructor(props) {
super(props);
this.state = {
counter: 0,
};
}
but1 = () => {
this.setState({ counter: this.state.counter + 1 });
};
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>Counter:{this.state.counter}</Text>
<Button
title="Increment"
onPress={this.but1}
accessibilityLabel="increment"
color="blue"
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontSize: 20,
fontWeight: 'bold',
},
});
Working App: Expo Snack
Please take a look at https://reactjs.org/docs/react-component.html#setstate
Remove this from your code and let only state.count + 1
An example I did in freedcodecamp.
handleChange(event){
//event.target.value
this.setState({
input: event.target.value
});
}
// Change code above this line
render() {
return (
<div>
{ /* Change code below this line */}
<input value={this.state.input} onChange={(e) => this.handleChange(e)}/>
That is because you are using a function component. You have to either use a class based component (React class and function components) or switch over to React hooks with the useState hook.
Here's the example with a class based component:
import * as React from 'react';
import { StyleSheet, Button, Alert } from 'react-native';
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
export default class TabTwoScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
counter: 0
}
}
but1() {
this.setState({ counter: this.state.counter + 1 });
};
render() {
return (
<View style={styles.container}>
<Text style={styles.title}>Counter:{state.counter}</Text>
<Button
title="Increment"
onPress={this.but1}
accessibilityLabel="increment"
color="blue"
/>
</View>
);
}
}
And here's with React hooks:
import React, {useState} from 'react';
import { StyleSheet, Button, Alert } from 'react-native';
import EditScreenInfo from '../components/EditScreenInfo';
import { Text, View } from '../components/Themed';
export default function TabTwoScreen() {
const [counter, setCounter] = useState(0);
const but1 = () => {
setCounter(counter + 1);
};
return (
<View style={styles.container}>
<Text style={styles.title}>Counter:{counter}</Text>
<Button
title="Increment"
onPress={but1}
accessibilityLabel="increment"
color="blue"
/>
</View>
);
}

React Native Delete Function not working as intended

The intended function is that it would just delete the one goal that is clicked but for some odd reason it decides onPress to delete all goals listed.
I am following this tutorial https://www.youtube.com/watch?v=qSRrxpdMpVc and im stuck around 2:44:45. If anyone else has done this tutorial and or can see my problem an explanation would be greatly appreciated. :)
Program
import React, { useState } from "react";
import {
StyleSheet,
Text,
View,
Button,
TextInput,
ScrollView,
FlatList
} from "react-native";
import GoalItem from "./components/GoalItem";
import GoalInput from "./components/GoalInput";
export default function App() {
const [courseGoals, setCourseGoals] = useState([]);
const addGoalHandler = goalTitle => {
setCourseGoals(currentGoals => [
...currentGoals,
{ key: Math.random().toString(), value: goalTitle }
]);
};
const removeGoalHander = goalId => {
setCourseGoals(currentGoals => {
return currentGoals.filter((goal) => goal.id !== goalId);
});
};
return (
<View style={styles.screen}>
<GoalInput onAddGoal={addGoalHandler} />
<FlatList
keyExtractor={(item, index) => item.id}
data={courseGoals}
renderItem={itemData => (
<GoalItem
id={itemData.item.id}
onDelete={removeGoalHander}
title={itemData.item.value}
/>
)}
></FlatList>
</View>
);
}
const styles = StyleSheet.create({
screen: {
padding: 80
}
});
Function
import React from "react";
import { View, Text, StyleSheet, TouchableOpacity } from "react-native";
const GoalItem = props => {
return (
<TouchableOpacity onPress={props.onDelete.bind(this, props.id)}>
<View style={styles.listItem}>
<Text>{props.title}</Text>
</View>
</TouchableOpacity>
);
};
const styles = StyleSheet.create({
listItem: {
padding: 10,
backgroundColor: "lightgrey",
borderColor: "grey",
borderRadius: 5,
borderWidth: 1,
marginVertical: 10
}
});
export default GoalItem;
When updating state, you have to pass new array so component can detect changes and update view
const removeGoalHander = goalId => {
setCourseGoals(currentGoals => {
const newGoals = currentGoals.filter((goal) => goal.id !== goalId);
return [...newGoals];
});
};

React Native changing background color according to data that comes through http request from server

I am new at React Native.
I'm working on a code that will change the background color of a box (card) according to the data that I will get from API. I want to check first if the title is like 'Taylor' make background red , if it is 'Fearless' make it green and so on.
Here is the API that I got information from :
http://rallycoding.herokuapp.com/api/music_albums
This is the code divided into several files.
First of them index.js
// Import a library to help to create a component
import React from 'react';
import { Text, AppRegistry, View } from 'react-native';
import Header from './src/components/header.js';
import AlbumList from './src/components/AlbumList.js'
// create a component
const App = () => (
<View>
<Header headerText={'Smart Parking'}/>
<AlbumList />
</View>
);
//render it to the device
AppRegistry.registerComponent('albums2', () => App);
second is AlbumList.js
import React, { Component } from 'react';
import { View } from 'react-native';
import axios from 'axios';
import AlbumDetail from './AlbumDetail.js'
class AlbumList extends Component {
state = { albums: [] };
componentWillMount() {
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({ albums: response.data }) );
}
renderAlbums() {
return this.state.albums.map(album =>
<AlbumDetail key={album.title} album={album} />
);
}
render() {
return(
<View>
{this.renderAlbums()}
</View>
);
}
}
export default AlbumList;
3rd is AlbumDetail.js
import React from 'react';
import {Text, View} from 'react-native';
import Card from './Card.js'
const AlbumDetail = (props) => {
return(
<Card>
<Text> {props.album.title} </Text>
</Card>
);
};
export default AlbumDetail;
4th is card which I need to change background of it
import React from 'react';
import { View } from 'react-native';
const Card = (props) => {
return (
<View style={styles.containerStyle}>
{props.children}
</View>
);
};
const styles = {
containerStyle:{
borderWidth: 1,
borderRadius: 2,
backgroundColor: '#ddd',
borderBottomWidth: 0,
shadowColor: '#000',
shadowOffset: {width: 0, height:2 },
shadowOpacity: 0.1,
shadowRadius: 2,
elevation: 1,
marginLeft: 5,
marginRight: 5,
marginTop: 10
}
};
export default Card;
last one is header
// Import libraries for making components
import React from 'react';
import { Text, View } from 'react-native';
// make a components
const Header = (props) => {
const { textStyle, viewStyle } = styles;
return(
<View style={viewStyle}>
<Text style={textStyle}>{props.headerText}</Text>
</View>
)
};
const styles ={
viewStyle:{
backgroundColor:'orange',
justifyContent: 'center',
alignItems: 'center',
height: 60,
},
textStyle: {
fontSize: 20
}
};
// make the component to the other part of the app
export default Header;
Basically you need to pass the title of the album as prop to the Card from the AlbumDetails component and then on each Card calculate the color to use and pass it in the style like this:
// AlbumDetails.js component
import React from 'react';
import {Text, View} from 'react-native';
import Card from './Card.js'
const AlbumDetail = (props) => {
return(
<Card title={props.album.title}>
<Text> {props.album.title} </Text>
</Card>
);
};
export default AlbumDetail;
// Card.js component
import React from "react";
import { View } from "react-native";
function calculateColor(title) {
let bgColor;
switch (title) {
case "Taylor":
bgColor = "red";
break;
case "Fearless":
bgColor = "green";
break;
default:
bgColor = "orange";
break;
}
return bgColor;
}
const Card = props => {
const { title } = props;
const backgroundColor = calculateColor(title);
return (
<View style={[styles.containerStyle, { backgroundColor: backgroundColor }]}>
{props.children}
</View>
);
};
const styles = {
containerStyle: {
borderWidth: 1,
borderRadius: 2,
backgroundColor: "#ddd",
borderBottomWidth: 0,
shadowColor: "#000",
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 2,
elevation: 1,
marginLeft: 5,
marginRight: 5,
marginTop: 10
}
};
export default Card;
Something like this should work:
Change the AlbumDetail to conditionally render the Card.
const AlbumDetail = props => {
if (props.album.title === 'Taylor') {
return (
<Card style={{ backgroundColor: 'red' }}>
<Text>{props.album.title}</Text>
</Card>
);
} else {
return (
<Card style={{ backgroundColor: 'green' }}>
<Text>{props.album.title}</Text>
</Card>
);
}
};
Override the default style of the card using the passed style prop.
const Card = props => {
return (
<View style={[styles.containerStyle, props.style]}>{props.children}</View>
);
};
accepted answer is great just its a bad habit to do things in render.
i also not sure since every title has a color why wouldnt the server send this in the object props in first place ? :)
class AlbumList extends Component {
state = { albums: [] };
componentDidMount() {
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(response=> Array.isArray(response.data) ? response.data : []) // alittle validation would not hurt :) !
.then(data => this.setState({ albums: data }) );
}
selectHeaderColorForAlbum( album ){
let headerColor = 'red';
// switch(album.title){ ..you logic }
return headerColor;
}
renderAlbums() {
return this.state.albums.map(album =>
<AlbumDetail key={album.title} album={album} color={this.selectHeaderColorForAlbum(album)} />
);
}
render() {
return(
<View>
{this.renderAlbums()}
</View>
);
}
}
const Card = (props) => {
return (
<View style={[styles.containerStyle,{color:props.headerColor}]}>
{props.children}
</View>
);
};
this is easier your logic will render only once.
also notice that react >16.0 depricated componentWillMount, so use DidMount

How to navigate page with React Native

I have a component for listing items, I want to add the function that can go to a different page, and that page has the detail about that item. Currently, this is my code for listing items.
import React, { Component } from 'react';
import { ScrollView } from 'react-native';
import axios from 'axios';
import CarDetail from './CarDetail';
const API_URL = 'http://localhost:3000';
class CarList extends Component {
state = { cars: [] };
componentWillMount() {
console.log('Mount');
axios.get(`${API_URL}/cars`)
.then(response => this.setState({ cars: response.data.cars }));
}
renderCars() {
return this.state.cars.map(car => <CarDetail key={car.id} car={car} />
);
}
render() {
console.log(this.state.cars);
return (
<ScrollView>
{this.renderCars()}
</ScrollView>
);
}
}
export default CarList;
and this is the code for describing items
import React from 'react';
import { Text, View, Image } from 'react-native';
import { Actions } from 'react-native-router-flux';
import Card from '../material/Card';
import CardSection from '../material/CardSection';
const CarDetail = ({ car }) => {
const imageURI = 'https://yt3.ggpht.com/-HwO-2lhD4Co/AAAAAAAAAAI/AAAAAAAAAAA/p9WjzQD2-hU/s900-c-k-no-mo-rj-c0xffffff/photo.jpg';
const { make, model } = car;
function showCarDetail() {
Actions.showCar();
}
return (
<Card>
<CardSection>
<View style={styles.containerStyle}>
<Image
style={styles.imageStyle}
source={{ uri: imageURI }}
/>
</View>
<View style={styles.headContentStyle}>
<Text
style={styles.headerTextStyle}
onPress={showCarDetail()}
>
{make}
</Text>
<Text>{model}</Text>
</View>
</CardSection>
<CardSection>
<Image
style={styles.picStyle}
source={require('./car.jpg')}
/>
</CardSection>
</Card>
);
};
const styles = {
headContentStyle: {
flexDirection: 'column',
justifyContent: 'space-around'
},
headerTextStyle: {
fontSize: 18
},
imageStyle: {
height: 50,
width: 50
},
containerStyle: {
justifyContent: 'center',
alignItems: 'center',
marginLeft: 10,
marginRight: 10
},
picStyle: {
height: 300,
flex: 1,
width: null
}
};
export default CarDetail;
How can I change my code for that? Can anyone give me an example?
You have to use some sort of navigation component. There are many out there, but personally I use the one that is built into React Native. https://facebook.github.io/react-native/docs/navigator.html

Categories

Resources