Passing in variables on mapped components? (React Native) - javascript

I have this code:
import React, { useState } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
export default function App() {
let str = "Hello ^world text '^Some^' '^Random^' '^Example^' '^Text^' '^Some^' '^more^' '^random^' '^example^' '^text^'!"
let arr = str.split(/\s/g)
let wordBits
const [highlightedWords, setHighlightedWords] = useState(["world", "example", "random"])
function highlighter(word) {
setHighlightedWords((prevState) => {
return(
[word, ...prevState]
)
})
}
return (
<View style={styles.container}>
<Text>
{arr.map((el) => {
wordBits = el.split("^")
token = wordBits[1]
return (
<Text>
{wordBits[0]}
<View style={
highlightedWords.includes(wordBits[1]) ?
styles.highlighted :
styles.regular
}>
<Text onPress={() => {highlighter(wordBits[1])}}>
{wordBits[1]}
</Text>
</View>
{wordBits[2]}{" "}
</Text>
)
})}
</Text>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
highlighted: {
backgroundColor: "yellow"
},
regular: {
color: "black"
}
});
I extract the word from surrounding characters and try to pass it in as a function on each component. But instead, it gets set to the final word that got mapped.
Is there a way to pass the words themselves, and not change as the variable changes?

Related

in react-native how to use body-pix

import { Camera, CameraType } from 'expo-camera';
import React, { useRef } from "react";
// import logo from './logo.svg';
import * as tf from "#tensorflow/tfjs";
import * as bodyPix from "#tensorflow-models/body-pix";
import { useState } from 'react';
import { Button, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
//AFTER IMPORT
export default function App() {
const [type, setType] = useState(CameraType.back);
const [permission, requestPermission] = Camera.useCameraPermissions();
const canvasRef = useRef(null);
//next part
const runBodysegment = async () => {
const net = await bodyPix.load();
console.log("BodyPix model loaded.");
// Loop and detect hands
setInterval(() => {
detect(net);
}, 100)
};
//next part
const detect = async (net) => {
const person = await net.segmentPersonParts(video);
console.log(person);
const coloredPartImage = bodyPix.toColoredPartMask(person);
bodyPix.drawMask(
canvasRef.current,
video,
coloredPartImage,
0.7,
0,
false
);
runBodysegment();
if (!permission) {
// Camera permissions are still loading
return <View />;
}
if (!permission.granted) {
// Camera permissions are not granted yet
return (
<View style={styles.container}>
<Text style={{ textAlign: 'center' }}>We need your permission to show the camera</Text>
<Button onPress={requestPermission} title="grant permission" />
</View>
);
}
function toggleCameraType() {
setType(current => (current === CameraType.back ? CameraType.front : CameraType.back));
}
return (
<View style={styles.container}>
<Camera style={styles.camera} type={type}>
<View style={styles.buttonContainer}>
<TouchableOpacity style={styles.button} onPress={toggleCameraType}>
<Text style={styles.text}>Flip Camera</Text>
</TouchableOpacity>
</View>
</Camera>
</View>
);
}
//next part
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
},
camera: {
flex: 1,
},
buttonContainer: {
flex: 1,
flexDirection: 'row',
backgroundColor: 'transparent',
margin: 64,
},
button: {
flex: 1,
alignSelf: 'flex-end',
alignItems: 'center',
},
text: {
fontSize: 24,
fontWeight: 'bold',
color: 'white',
},
});
};
I want to use body-pix in my react-native app for android .
can any one help me how to do it .
I want my app to open a camera and in my camera there will be a body body-pix working
in my android app
I want my react-native app to work properly with body-pix
I had try it many time time but I can't do it properly

I want to verify a value using text input from an array, but I am not getting an output

I want to input a value, which will be compared to my dummy data, and once the value is compared, i'll get an alert if the value is matched or not
//UPDATE - I have made some changes to the code, not the alert is working, but the values are not being matched. only getting the second alert - Error.
import { View, Text, FlatList, TextInput, StyleSheet, TouchableOpacity, Button } from 'react-native'
import React, {useState} from 'react'
import { CATEGORIES } from '../DummyData/dummy-data'
const renderGridItem = (itemData) =>{
return (
<View style={{marginVertical:5,marginVertical:15, flex:1, margin:15}}>
<Text style={{color:'black'}}>
{itemData.item.id}
</Text>
</View>
)
}
const Meals = props => {
const [text, onChangeText] = useState();
var onClick = () => {
if (renderGridItem === text){
alert("ID Matched");
}
else{
alert('Error')
}
}
console.log(text)
return (
<View>
<FlatList keyExtractor={(item, index) => item.id}
data={CATEGORIES}
numColumns={2}
renderItem={renderGridItem} />
<TextInput
style={styles.tip}
placeholder='Enter CNIC'
keyboardType='default'
onChangeText={onChangeText}
value={text}
/>
<TouchableOpacity style={styles.top} onPress={() => { ()=>onChangeText(text); onClick()} }>
<Text style={{textAlign:'center'}}>
Enter
</Text>
</TouchableOpacity>
</View>
)
}
const styles = StyleSheet.create({
tip:{
borderWidth:1,
marginVertical:50,
borderRadius:8
},
top:{
width:'30%',
borderWidth:1,
marginLeft:140,
padding: 10,
borderRadius:8
},
})
export default Meals
//Dummy-Data (Array)
import Data from "../Model/Data";
export const CATEGORIES = [
new Data('c1', 'Person 1', '#f5428d'),
new Data('c3', 'Person 2', '#f5a442'),
];
//Data
class Data {
constructor(id, title){
this.id=id,
this.title=title
}
}
export default Data
Please check the code it might be helpful to you.
import React, { useState, useEffect } from "react";
import {
StyleSheet,
SafeAreaView,
TextInput,
View,
Text,
Button,
TouchableOpacity,
} from "react-native";
const App = () => {
const [text, setText] = useState("");
function onPressButton() {
var result = DATA.some((item, index) => item.title == text);
if (result == true) {
alert("DATA Found");
} else {
alert("DATA not found");
}
}
return (
<SafeAreaView style={{ flex: 1 }}>
<View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}>
<TextInput
style={{ borderBottomWidth: 1, width: "90%", padding: 10 }}
placeholder="Enter Title"
onChangeText={(text) => setText(text)}
/>
<TouchableOpacity
style={{
width: 100,
height: 50,
borderWidth: 1,
justifyContent: "center",
alignItems: "center",
borderRadius: 10,
marginTop: 20,
}}
onPress={onPressButton}
>
<Text>Find</Text>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
const DATA = [
{ id: 1, title: "ABC" },
{ id: 2, title: "XYZ" },
];
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "white",
},
});
export default App;
OUTPUT:

React native `input` must be a function received undefined

I have an array which displays a list of jobs with the radio button(each).If I click any radio button I want to get its value so far I'm getting an error input must be a function received undefined. how can I achieve something like this in react native?
Code
import React, {useState} from 'react';
import {View, Text, TextInput, Image,Button,Body,Pressable,ScrollView,Switch} from 'react-native';
export default function Home({ navigation}){
let roles = navigation.getParam('roles')
const [isEnabled, setIsEnabled] = useState(false);
const toggleSwitch = () => setIsEnabled(previousState => !previousState);
const handleClick = (data, e) => {
alert(e.target.value, data);
}
<View>
{
Object.keys(roles).map((key) => {
return (
<View>
<View style={styles.XYQHC}>
<Text>{roles[key]['name']}</Text>
<Switch
trackColor={{ false: "#767577", true: "#81b0ff" }}
thumbColor={isEnabled ? "#f5dd4b" : "#f4f3f4"}
ios_backgroundColor="#3e3e3e"
onValueChange={toggleSwitch}
value={isEnabled}
/>
<input type="radio" name="roles" value={roles[key]['name']} defaultChecked={roles[key]['id'] == 3 ? true : false } onClick={handleClick.bind(this, roles[key]['name'])}/>
</View>
</View>
)
})
}
</View>
};
I had to edit a little bit to make it work and to assume some input data but here is a working example of your code:
import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
function RadioButton({ label, onPress, selected, style }) {
return (
<TouchableOpacity
style={[
{
flexDirection: 'row',
alignItems: 'center',
marginLeft: 12,
marginVertical: 20,
},
style,
]}
onPress={onPress}>
<View
style={{
height: 24,
width: 24,
borderRadius: 12,
borderWidth: 2,
borderColor: '#000',
alignItems: 'center',
justifyContent: 'center',
marginRight: 12,
}}>
{selected ? (
<View
style={{
height: 12,
width: 12,
borderRadius: 6,
backgroundColor: '#000',
}}
/>
) : null}
</View>
<Text>{label}</Text>
</TouchableOpacity>
);
}
export default function Home({ navigation }) {
// let status = navigation.getParam('status');
let status = 2;
// let roles = navigation.getParam('roles');
let roles = [
{
id: 1,
name: 'lawyer',
},
{
id: 2,
name: 'farmer',
},
{
id: 3,
name: 'architect',
},
];
const [isEnabled, setIsEnabled] = useState(false);
const [chosenRole, setChosenRole] = useState(false);
useEffect(() => {
roles.find((role) => {
if (role.id === status) {
setChosenRole(role);
return true;
}
return false;
});
}, []);
const handleClick = (data) => {
console.log(data);
setChosenRole(data);
};
return (
<View style={{ marginTop: 30 }}>
{roles.map((role) => {
return (
<View>
<RadioButton
label={role.name}
selected={role.name === chosenRole.name}
onPress={() => handleClick(role)}
/>
</View>
);
})}
</View>
);
}

How to use react-native-action-sheet with hooks

I'm trying to use https://github.com/expo/react-native-action-sheet in a functional component using the provided hook useActionSheet(). I'm already using the class components version without any problem but I'd like to switch to functional.
React version is 16.9.0
This is my component
import {
connectActionSheet,
useActionSheet,
} from "#expo/react-native-action-sheet";
import React, { Component } from "react";
import { View, Text, SafeAreaView } from "react-native";
import TaButton from "../components/TaButton";
import { typography, styles, buttons } from "../components/Styles";
const UploadUI: React.FC<{
description: string;
label: string;
}> = (props) => {
const { showActionSheetWithOptions } = useActionSheet();
const openActionSheet = () => {
console.log("TEST - Choosing action now");
const options = [
"Scegli dalla libreria",
"Scatta una foto",
"Carica un file",
"Annulla",
];
//const destructiveButtonIndex = 0;
const cancelButtonIndex = options.length - 1;
showActionSheetWithOptions(
{
options,
cancelButtonIndex,
//destructiveButtonIndex,
},
(buttonIndex) => {
// Do something here depending on the button index selected
switch (buttonIndex) {
case 0:
console.log('Case 0')
return;
case 1:
console.log("Case 1");
return;
case 2:
console.log("Case 2");
return;
default:
}
}
);
};
const { description, label } = props;
return (
<View style={{ flexDirection: "row", height: 50, marginBottom: 30 }}>
<View style={{ flex: 0.7, justifyContent: "center" }}>
<Text style={typography.body}>{description}</Text>
</View>
<View style={{ flex: 0.3 }}>
<TaButton
style={buttons.primary}
labelStyle={buttons.primaryLabel}
onPress={() => openActionSheet()}
label={label}
/>
</View>
</View>
);
};
const URWStep4: React.FC = (props) => {
return (
<SafeAreaView style={styles.container}>
<View style={styles.container}>
<View style={{ paddingVertical: 30, marginBottom: 20 }}>
<Text style={typography.title}>
Ci serviranno alcuni documenti per verificare la tua identità
</Text>
</View>
<UploadUI
description="Carta d'identità - Fronte"
label="Carica"
></UploadUI>
<UploadUI
description="Carta d'identità - Retro"
label="Carica"
></UploadUI>
</View>
</SafeAreaView>
);
};
export default connectActionSheet(URWStep4);
When clicking on buttons, the sentence "TEST - Choosing action now" is logged ad expected, but nothing more happens. The actionsheet does not open.
Check you have wrapped your top-level component with <ActionSheetProvider /> even when using hooks
https://github.com/expo/react-native-action-sheet#1-wrap-your-top-level-component-with-actionsheetprovider-
using useRef, I saw the issue in lib and Allanmaral's answer:
import ActionSheet from 'react-native-actionsheet'
const Demo = (props) => {
const refActionSheet = useRef(null);
showActionSheet = () => {
if (refActionSheet.current) {
refActionSheet.current.show();
}
}
return (
<View>
<Text onPress={this.showActionSheet}>Open ActionSheet</Text>
<ActionSheet
ref={refActionSheet}
title={'Which one do you like ?'}
options={['Apple', 'Banana', 'cancel']}
cancelButtonIndex={2}
destructiveButtonIndex={1}
onPress={(index) => { /* do something */ }}
/>
</View>
)
}

Pass data between two components in React Native

I have a component that encapsulates three components one of them is the DrawerLayoutAndroid. Now I want to pass the reference of the drawer from the drawer component to the main component and then pass it to the header component so I can trigger it from the header component.
I have no idea how to do that.
Here is the main component 'cases.js'
import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import Header from '#components/header';
import BottomBar from '#components/bottom-bar';
import SideBar from '#components/drawer';
export default class Cases extends Component {
state = {
title : 'Cases'
}
change_text = () => {
this.setState({ title : 'Test' })
}
open_drawer = (ref) => {
ref.openDrawer();
}
close_drawer = (ref) => {
ref.closeDrawer();
}
render() {
return (
<SideBar style={ styles.container }>
<Header title={ this.state.title } change_text={ this.change_text } open={ this.state.side_bar } />
<View style={ styles.body }>
<Text style={ styles.text }> { this.state.name } </Text>
<TouchableOpacity onPress={ () => this.change_text() } style={ styles.button }>
<Text> Change State </Text>
</TouchableOpacity>
</View>
<BottomBar ref={ this.state.side_bar } />
</SideBar>
)
}
}
const styles = StyleSheet.create({
container : {
flex : 1,
flexDirection: 'column',
},
body : {
flex : 1,
backgroundColor: '#ccc',
justifyContent: 'center',
alignItems: 'center'
},
text : {
color : '#fff'
},
button : {
backgroundColor : '#eee',
paddingVertical: 5,
paddingHorizontal: 10
}
})
Here is my header:
import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Image } from 'react-native';
import DrawerLayoutAndroid from 'DrawerLayoutAndroid';
import LinearGradient from 'react-native-linear-gradient';
export default class Header extends Component {
change_text = () => {
this.props.change_text();
}
open = ()
render () {
return (
<LinearGradient start={{x: 0, y: 0}} end={{x: 1, y: 0}} colors={['#a4d294', '#3ac6f3']} style={ styles.header }>
<TouchableOpacity onPress={ () => this.props.change_text() }>
<Image source={ require('#media/images/add.png') } style={ styles.add_button } />
</TouchableOpacity>
<Text style={ styles.title }> { this.props.title } </Text>
<TouchableOpacity onPress={ () => this.props.open() }>
<Image source={ require('#media/images/more.png') } style={ styles.more_button } />
</TouchableOpacity>
</LinearGradient>
)
}
}
const styles = StyleSheet.create({
header : {
height: 70,
backgroundColor: '#eee',
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center'
},
title : {
color : '#fff',
textAlign: 'center',
fontSize: 20,
letterSpacing: 3
},
add_button : {
width: 30,
height: 30,
marginHorizontal: 10
},
more_button : {
width: 30,
height: 30,
marginHorizontal: 10
}
})
And here is my drawer.js
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import DrawerLayoutAndroid from 'DrawerLayoutAndroid';
import LinearGradient from 'react-native-linear-gradient';
export default class Drawer extends Component {
render () {
const NavigationMenu = (
<LinearGradient start={{x: 0, y: 0}} end={{x: 0, y: 1}} colors={['#a4d294', '#3ac6f3']} style={{ flex: 1 }}>
<View style={{ flex : 6, justifyContent: 'center' }}>
<Text>He There</Text>
</View>
</LinearGradient>
)
return (
<DrawerLayoutAndroid
drawerWidth={250}
drawerPosition={ DrawerLayoutAndroid.positions.Right }
renderNavigationView={ () => NavigationMenu }
ref={ (drawer) => this.props.ref = drawer }
>
{ this.props.children }
</DrawerLayoutAndroid>
)
}
}
I am going to answer your question by giving a simple example.
Lets take 2 components parent and child. You want to pass some message from parent to child and get a callback from child to parent when an event occurs in child.
export default class Parent extends React.Component<any, any> {
callback (paramFromChild) => {
// implement what to do when certain event occurs in child component
}
render () {
<View>
<Child message={"some text"} callbackFromChild={this.callback}/>
</View>
}
}
Child component
Interface childProps {
message: string
callbackFromChild(paramFromChild);
}
export default class Child extends React.Component<childProps, any> {
render () {
<View>
<Button title={this.props.message} onPress={this.props.callbackFromChild("some message from child")}/>
</View>
}
}
In this way you can communicate between different components using props.

Categories