(React) How to send variable value to other component? - reactjs

It's a nice day.
//App.js
import React, { useEffect, useRef, useState, createContext, useContext } from "react"
import {
StyleSheet, StatusBar, View, Text, Linking, Button,
SafeAreaView, TouchableOpacity, RefreshControl } from 'react-native';
export default function App() {
const wannaConst = 'qwqw'
return (
<View>
<Text>
Good Good
</Text>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}
})
//screens > Home > Home.js
import React from 'react'
import { View, Text } from 'react-native'
const Home = () => {
return (
<View>
<Text>{wannaConst}</Text>
</View>
)
}
export default Home
I wanna use App.js's wannaConst's Variable Value
at screens > Home > Home.js
if wannaConst = 'qrqr',
Home components return [qrqr] screens.
or wannaConst = 'help me :(',
Home components return [help me :(] screens...
and so on.
How to solve it? use Redux? or ContextAPI?
Thx for reading.

Both way will work OK. If your project is small or middle-sized, context API will work without any problem.
AppContext.jsx
import {createContext} from 'react';
export default createContext({
wannaConst: 'qwqw'
}); // provide initial value
App.jsx
import React, { useEffect, useRef, useState, createContext, useContext, useCallback } from "react"
import {
StyleSheet, StatusBar, View, Text, Linking, Button,
SafeAreaView, TouchableOpacity, RefreshControl } from 'react-native';
import AppContext from './AppContext'
export default function App() {
// You can manage AppContext state here
const [contextValue, setContextValue] = useState({
wannaConst: 'qrqr' // provide initial value here, default value in AppContext.jsx will be overwritten
}};
// context values are also React states. You can update the state like any other React states
const handlePressButton = useCallback(
() => setContextValue({wannaConst: 'good good'}),
[]);
return (
<AppContext.Provider value={contextValue}>
<View>
<Text>
Good Good
</Text>
<Button onPress={handlePressButton}>
Change context to 'good good'
</Button>
</View>
//... child components that are going to consume AppContext value
</AppContext.Provider>
)
}
Be aware that screens/Home/Home.js should be nested inside AppContext.Provider. Most of the case, it will be like so, because you will create stack/tab navigations and list all the navigation routes and screens under App.jsx.
Home.jsx
import React, {useContext} from 'react'
import { View, Text } from 'react-native'
import AppContext from './AppContext';
const Home = () => {
const appContext = useContext(AppContext);
return (
<View>
<Text>{appContext.wannaConst}</Text>
</View>
)
}
export default Home
Using redux is somewhat difficult but it is almost mandatory in enterprise apps. Here you can find a good source for modern react and redux

Related

React native modal datetime picker not showing up when opened

I am building my first react native app and for my app to work I need to use react-native-modal-datetime-picker. here's my code-
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, FlatList, Image, Button, Pressable, ScrollView, } from 'react-native';
import React, {useState, useEffect, useCallback, Component} from 'react'
import { TextInput } from 'react-native-gesture-handler';
import RNPickerSelect from 'react-native-picker-select';
import * as ImagePicker from 'expo-image-picker';
import { FontAwesomeIcon } from '#fortawesome/react-native-fontawesome';
import { faSquare } from '#fortawesome/free-regular-svg-icons';
import * as Device from 'expo-device';
import DateTimePickerModal from 'react-native-modal-datetime-picker'
export default function Profile(props) {
const [ openD, setOpenD ] = useState(false)
const [ dob, setDob ] = useState(new Date())
const dateselect = (date) => {
setDob(date)
setOpenD(false)
}
return (
<View style={styles.scroll}>
<ScrollView style={styles.scroll}>
<Text style={styles.label}>Date of Birth:</Text>
<Pressable onPress={() => setOpenD(true)} title="date">
<Text style={styles.input}>{ dob.toLocaleDateString() }</Text>
</Pressable>
<DateTimePickerModal
isVisible={openD}
mode="date"
onConfirm={dateselect}
onCancel={() => setOpenD(false)}
/>
</ScrollView>
<StatusBar style="auto"/>
</View>
)
}
When I try to open the date picker, I get only the confirm button on the bottom and nothing else is showing up. It worked for me before and now it doesn't. I dont know how can I solve this issue?
It looks like you're missing a closing parenthesis. Try adding a ) after your </View> and reload the app (you can press rr on your keyboard with your app open if you're using an iOS simulator). You may need to restart your bundler as well.

React Native Component Exception

I got this error message while working on the other file
Error: Couldn't find a 'component', 'getComponent' or 'children' prop for the screen 'Store'. This can happen if you passed 'undefined'. You likely forgot to export your component from the file it's defined in, or mixed up default import and named import when importing.
my Store file - screen/Store.js:
import React from "react";
import {
StyleSheet,
SafeAreaView,
View,
Text,
TouchableOpacity,
Image,
Animated
} from "react-native";
import { isIphoneX } from 'react-native-iphone-x-helper'
import { icons, COLORS, SIZES, FONTS } from '../constants'
const Store = ({ route, navigation }) => {
...
export default Store;
my Home file - screens/Home.js
import React from "react";
import {
SafeAreaView,
View,
Text,
StyleSheet,
TouchableOpacity,
Image,
FlatList
} from "react-native";
import { icons, images, SIZES, COLORS, FONTS } from '../constants'
const Home = ({ navigation }) => {
...
export default Home;
my navigation file -navigation/tab.js:
import React from 'react';
import {
View,
Image,
TouchableOpacity
} from 'react-native';
import { createBottomTabNavigator, BottomTabBar } from "#react-navigation/bottom-tabs"
import Svg, { Path } from 'react-native-svg';
import { isIphoneX } from 'react-native-iphone-x-helper';
import {Home, User} from '../screens'
import { COLORS, icons } from "../constants"
const Tabs = () => {
...
}
export default Tabs
and my App.js file in the main folder
import React from 'react';
import { createStackNavigator } from "#react-navigation/stack";
import { NavigationContainer } from '#react-navigation/native';
import { Store, OrderDelivery, User } from './screens';
import Tabs from './navigation/tabs';
const Stack = createStackNavigator();
const App = () => {
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerShown: false
}}
initialRouteName={'Home'}
>
<Stack.Screen name="Home" component={Tabs} />
<Stack.Screen name="Store" component={Store} />
<Stack.Screen name="OrderDelivery" component={OrderDelivery} />
<Stack.Screen name="User" component={User} />
</Stack.Navigator>
</NavigationContainer>
)
}
export default App;
I understand what the message means but I dont get what did I do wrong and how to fix it, please help.
Are you sure you imported React in Store.js, try adding the import React from 'react';
Try to import Store from './screens/Store';

useSpring Hook returns 'You atttempted to set lastVelocity' with the value 0 error

I'm currently getting started with useSpring in react native . I have the following very simple component
import React from 'react'
import { View, Text } from 'react-native'
import {useSpring, animated} from 'react-spring'
const Pane = () => {
const props = useSpring(() => ({opacity: 1}))
return (
<View style={{ props }}>
<Text> 'test' </Text>
</View>
)
}
export default Pane;
However, rendering this in my simulator for React Native I get the following: What am I doing wrong?
You wrap the content of the style prop in an extra object, which is not needed, just pass the props as prop.
Also, i believe you have to set the props to an animated view instead of the regular RN view.
import React from 'react'
import { View, Text } from 'react-native'
import {useSpring, animated} from 'react-spring'
const AnimatedView = animated(View)
const Pane = () => {
const props = useSpring(() => ({opacity: 1}))
return (
<AnimatedView style={props}>
<Text> 'test' </Text>
</AnimatedView>
)
}
export default Pane;
If your React version is 16.7 or higher, you can use hooks.
import React, { useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default function App() {
const [opacity, setOpacity] = useState(0);
return (
<View style={{ opacity }}>
<Button
onPress={() => setOpacity(opacity + 1)}
title="Click me"
color="red"
/>
</View>
);
}

Element type is invalid: expected a string [...] Check the render method of 'BurpSimV3'

i made a new app with the latest version of react native and it works. Then, i choose to downgrade and create a new app with version 0.44 for compatibility of certain components.. and this:
Error:
Here the code of my index
And here my ScenaPrincipale.js
import React, { Component } from 'react';
import {
StatusBar,
ImageBackground,
StyleSheet
} from 'react-native';
import Titolo from './titolo';
import Descrizione from './descrizione';
import BottonArea from './bottonarea';
import Banner from './banner';
export default class ScenaPrincipale extends Component {
render() {
return(
<ImageBackground source={require('../imgs/garfield.jpg')} style={styles.container}>
<StatusBar hidden/>
<Titolo/>
<Descrizione/>
<BottonArea/>
<Banner/>
</ImageBackground>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
}
});
What can i do?

Unable to Navigate to new screen from within FlatList

My first page with FlatList is :
import React, { Component } from 'react';
import { View, StyleSheet, FlatList, Text, TouchableHighlight } from 'react-native';
import { StackNavigator } from 'react-navigation';
import MoreInfo from './MoreInfo';
export default class Page1 extends Component {
constructor(props){
super(props);
}
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<FlatList
data={users}
renderItem={
({item}) =>
<TouchableHighlight onPress={() => navigate('MoreInfo', { name: 'Jane' })}>
<Text style={styles.welcome}> {item.name} </Text>
</TouchableHighlight>
}
keyExtractor={item => item.index}
>
</FlatList>
</View>
);
}
}
const App = StackNavigator({
Page1: {screen: Page1},
MoreInfo: { screen: MoreInfo },
})
I am able to get the data displayed in a FlatList without using the navigation. But when I put Navigation and click any item on the list, I get the error:
Please help. Trying this since 3 days.
My index.android.js is
import React, { Component } from 'react';
import { AppRegistry} from 'react-native';
import MyApp2 from './src/components/MyApp2';
const MyApp2 = StackNavigator({
Page1: {screen: Page1},
MoreInfo: { screen: MoreInfo },
})
AppRegistry.registerComponent('MyApp2', () => MyApp2);
And My './src/components/MyApp2' is:
import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput, ScrollView, Alert,
FlatList, ActivityIndicator, Image,TouchableOpacity } from 'react-native';
import { Container } from 'native-base';
import AppHeader from './AppHeader';
import AppBody from './AppBody';
import AppFooter from './AppFooter';
export default class MyApp2 extends Component{
render(){
return(
<Container>
<AppHeader />
<AppBody/>
<AppFooter />
</Container>
)
}
}
I further have some tabs in the AppBody and including Page1 somewhere there. How would I go about it?
It doesn't look like you're importing Page1 anywhere and it's odd that you're importing MyApp2 and then defining a const for the StackNavigator that is also called MyApp2. I cannot test this since there are other files being imported, but I believe you just need to:
fix your imports,
fix your naming conflicts,
register all of your screens with StackNavigator so they all have access to the navigation prop,
and register the StackNavigator for your AppRegistry.
Try this:
Leave ./src/components/MyApp2 as is. Then make these edits (I'll be making the assumption that MyApp2, Page1, and MoreInfo are all located in ./src/components/:
Page1 file (whatever that is named):
import React, { Component } from 'react';
import { View, StyleSheet, FlatList, Text, TouchableHighlight } from 'react-native';
export default class Page1 extends Component {
constructor(props){
super(props);
}
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<FlatList
data={users}
renderItem={
({item}) =>
<TouchableHighlight onPress={() => navigate('MoreInfo', { name: 'Jane' })}>
<Text style={styles.welcome}> {item.name} </Text>
</TouchableHighlight>
}
keyExtractor={item => item.index}
>
</FlatList>
</View>
);
}
}
index.android.js
import React, { Component } from 'react';
import { AppRegistry} from 'react-native';
import { StackNavigator } from 'react-navigation';
// Making an assumption for where these files are located
// since it's not in the original question.
import MyApp2 from './src/components/MyApp2';
import MoreInfo from './src/components/MoreInfo';
import Page1 from './src/components/Page1';
/**
* This presumes that MyApp2 is the screen that will be loaded first.
* I don't know how you are getting to Page1, but it will be accessible
* if you navigate to it like so:
* this.props.navigation.navigate('Page1')
* Once there, the navigate() in the FlatList of Page1 should work as written.
*/
const RootNavigator = StackNavigator({
MyApp2: {screen: MyApp2},
Page1: {screen: Page1},
MoreInfo: { screen: MoreInfo },
})
AppRegistry.registerComponent('MyApp2', () => RootNavigator);
In your index.android.js file , you are using StackNavigator but you have not imported it .
use :
import { StackNavigator } from react-navigation

Resources