passing a prop from index into header component - react-native

I'm following a udemy tutorial on react-native.
I'm trying to pass a prop from my index.js into my header.js. The header should say, "Albums". But is is always showing up blank.
If I remove {props.headerText} from header.js and replace it with
"Albums"
then it works. But I'm trying to make the component reusable per the tutorial instructions.
note: I'm using Create React Native App and this is on an android emulator.
App.js
import React from 'react';
import { View } from 'react-native';
import Header from './src/components/header';
export default class App extends React.Component {
render() {
return (
<Header />
);
}
}
index.js
import React from 'react';
import { Text, AppRegistry } from 'react-native';
import Header from './src/components/header';
const App = () => (
<Header headerText={'Albums'} />
);
AppRegistry.registerComponent('albums', () => App);
header.js
import React from 'react';
import { Text, View } from 'react-native';
const Header = (props) => {
const { textStyle, viewStyle } = styles;
return (
<View style={viewStyle}>
<Text style={textStyle}>{props.headerText}</Text>
</View>
);
};
const styles = {
viewStyle: {
justifyContent: 'center'
},
headerStyle: {
fontSize: 20
}
};
export default Header;
Am I missing anything? I've been over and over each file line by line and I can't find any issues.
Thanks!

I would suggest you
const Header = ({props}) => {
const { textStyle, viewStyle } = styles;
return (
<View style={viewStyle}>
<Text style={textStyle}>{props.headerText}</Text>
</View>
);
};
And to pass props ;
const App = () => (
<Header props={someProps} />
);

Related

React-Native app doesn't work properly with external packages

It works very normally when I use React Hooks or when I use react-native's Component, Hooks.
But when I call a function or Component from external packages such as Axios from my code, the app seems to be broken in that state. (or an empty screen)
I used react-native-cli.
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* #format
* #flow strict-local
*/
import React, {useState, useEffect} from 'react';
import type {Node} from 'react';
import {
SafeAreaView,
ScrollView,
StatusBar,
Text,
useColorScheme,
View,
Center,
} from 'react-native';
import Axios from 'axios';
import {
Colors,
Header,
} from 'react-native/Libraries/NewAppScreen';
const App: () => Node = () => {
const isDarkMode = useColorScheme() === 'dark';
const [text, setText] = useState("");
const backgroundStyle = {
backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
};
useEffect(() => {
const fetch = async () => {
const {data} = await Axios.get(...); // broken
setText(data.result);
};
fetch();
}, []);
return (
<SafeAreaView style={backgroundStyle}>
<StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} />
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={backgroundStyle}>
<Header />
<View
style={{
backgroundColor: isDarkMode ? Colors.black : Colors.white,
}}>
<Text>{text}</Text>
{/*
this Text Component is still empty.
*/}
</View>
</ScrollView>
</SafeAreaView>
);
};
export default App;
How can I solve this problem?

react native expo google font usefont.js text error?

I'm doing a project in react native but i have an issue with my expo google font. I'm pretty new to expo so I have basically no idea on how to fix this bug. The bug only appears on IOS (don't know about android) and works fine on web. The bug appears to be inside useFonts.js which is a file that's part of the expo-google-font.
One of my files using expo-google-font.
import React from "react";
import { Text, TouchableOpacity, Image, StyleSheet } from "react-native";
import { useFonts, Inter_300Light } from "#expo-google-fonts/inter";
import { DefaultWidth } from "./DefaultWidth";
export default function AppleButton() {
let [fontsLoaded] = useFonts({ Inter_300Light });
if (!fontsLoaded) {
return null;
}
return (
<TouchableOpacity style={styles.appleBtnWrapper}>
<Image
style={styles.appleBtnImage}
source={require("../../../assets/third-party-icon/apple.png")}
/>
<Text style={styles.appleBtnText}>Fortsæt med Apple</Text>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
appleBtnText: {
color: "#fff",
fontWeight: "bold",
textAlign: "center",
fontFamily: "Inter_300Light",
fontSize: 16,
},
});
The useFonts.js use useEffect. These are the bugs I'm getting:
Here is the useFonts.js
import { useEffect, useState } from 'react';
import { loadAsync } from 'expo-font';
/**
* Load a map of custom fonts to use in textual elements.
* The map keys are used as font names, and can be used with `fontFamily: <name>;`.
* It returns a boolean describing if all fonts are loaded.
*
* Note, the fonts are not "reloaded" when you dynamically change the font map.
*
* #see https://docs.expo.io/versions/latest/sdk/font/
* #example const [loaded, error] = useFonts(...);
*/
export function useFonts(map) {
let [loaded, setLoaded] = useState(false);
let [error, setError] = useState(null);
useEffect(() => {
loadAsync(map)
.then(() => setLoaded(true))
.catch(setError);
}, []);
return [loaded, error];
}
Here is my App.tsx
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import {registerRootComponent} from 'expo'
import Navigation from './routes'
export default function App() {
return (
<Navigation/>
);
}
registerRootComponent(App);
Firstly install expo-app-loading from here
Then For your fonts create a folder called hooks where your App.js is located and inside that create a file useFonts.js
In useFonts.js write like this -
import * as Font from 'expo-font';
import { Inter_300Light } from '#expo-google-fonts/inter';
export default useFonts = async () => {
await Font.loadAsync({
Inter_300Light: Inter_300Light,
});
};
Your App.tsx should look like this
import { StatusBar } from 'expo-status-bar';
import React, { useState } from 'react';
import { registerRootComponent } from 'expo';
import AppLoading from 'expo-app-loading';
import useFonts from './hooks/useFonts';
import Navigation from './routes';
export default function App() {
const [IsReady, SetIsReady] = useState(false);
const FontLoading = async () => {
await useFonts(); // Font is being loaded here
};
if (!IsReady) {
return (
<AppLoading
startAsync={FontLoading}
onFinish={() => SetIsReady(true)}
onError={() => {}}
/>
);
}
return <Navigation />;
}
registerRootComponent(App);
Now if you want to use these fonts in any files then just simply write the name of the font. You don't need to Import font in every page
For example, your page which uses fonts should look like this
import React from 'react';
import { Text, TouchableOpacity, Image, StyleSheet } from 'react-native';
import { DefaultWidth } from './DefaultWidth';
export default function AppleButton() {
return (
<TouchableOpacity style={styles.appleBtnWrapper}>
<Image
style={styles.appleBtnImage}
source={require('../../../assets/third-party-icon/apple.png')}
/>
<Text style={styles.appleBtnText}>Fortsæt med Apple</Text>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
appleBtnText: {
color: '#fff',
fontWeight: 'bold',
textAlign: 'center',
fontFamily: 'Inter_300Light', // Name of the font..Simple
fontSize: 16,
},
});

How to Use method of functional component into class component in react native?

I am working in one react native project in which, I want to make common component for show loading indicator (for inform user to wait until process done.)
For that , I have make one js file that is common for my project
Look like below :
Loader.JS : Common functional component in react native
import React, {useState} from 'react';
import {View, StyleSheet, ActivityIndicator} from 'react-native';
import {loaderColor} from './app.constants';
const Loader = () => {
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color={loaderColor} />
</View>
);
};
const UseLoader = () => {
const [visible, setVisible] = useState(true);
const showLoader = () => setVisible(true);
const hideLoader = () => setVisible(false);
const loader = visible ? <Loader /> : null;
return [loader, showLoader, hideLoader];
};
const styles = StyleSheet.create({
loadingContainer: {
backgroundColor: 'red',
flex: 1,
position: 'absolute',
...StyleSheet.absoluteFillObject,
alignItems: 'center',
justifyContent: 'center',
zIndex: 100,
padding: 10,
},
});
export default UseLoader;
And my class component is look like this :
import React, {Component} from 'react';
import {View} from 'react-native';
// import {UseLoader} from '../UseLoader';
import '../UseLoader';
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
};
}
componentDidMount() {
[loader, showLoader , hideLoader] = UseLoader;
this.callApi()
}
callApi() {
...
}
render() {
return (
<View style={styles.body}>
{loader}
</View>
);
}
}
I have tried to import functional component in both way But failed to use it.
Is any solution that can Import functional component in class component in react native ?
you can use this.
You can add a ref to the child component:
<loader ref='loader' {...this.props} />
Then call the method on the child like this:
<Button onPress={this.refs.loader.myfunc} />
Same functionality, but instead of using a String to reference the component, we store it in a global variable instead.
<loader ref={loader => {this.loader = loader}} {...this.props} />
<Button onPress={this.loader.myfunc} />
If you want to do it common, change the state on the class component, where you send if it is visible or not, like this:
const Loader = (props) => {
if(props.show){
return (
<View style={styles.loadingContainer}>
<ActivityIndicator size="large" color={loaderColor} />
</View>
);
}else{
return null;
}
};
and in your class component
import React, {Component} from 'react';
import {View} from 'react-native';
// import {UseLoader} from '../UseLoader';
import '../UseLoader';
export default class Home extends Component {
constructor(props) {
super(props);
this.state = {
};
}
componentDidMount() {
this.setState({showLoading:true});
this.callApi()
}
callApi() {
...
}
render() {
return (
<View style={styles.body}>
<loader show={this.state.showLoading} />
</View>
);
}
}

Disable console log in react navigation

I'm using react navigation for my app development. When i run log-android, it keeps logging something like this.
Navigation Dispatch: Action: {...}, New State: {...}
which is from createNavigationContainer.js line 150.
I've run through github and document said it could be done by by setting onNavigationStateChange={null} on a top-level navigator.
How can i achieve this by setting onNavigationStateChange={null} and where should i set it?
I've try to set like below, but it the page will not be able to redirect to other page.
export default () => {
<App onNavigationStateChange={null} />
}
Below are my app.js code
import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View } from 'react-native';
import { StackNavigator,DrawerNavigator } from 'react-navigation';
import DrawerContent from './components/drawer/drawerContent.js';
import News from './components/news/home.js';
const drawNavigation = DrawerNavigator(
{
Home : {
screen : News ,
navigationOptions : {
header : null
}
}
},
{
contentComponent: props => <DrawerContent {...props} />
}
)
const StackNavigation = StackNavigator({
Home : { screen : drawNavigation,
navigationOptions: {
header: null
}
}
});
export default StackNavigation;
This is my drawerContent.js
import React, {Component} from 'react'
import {View,Text, StyleSheet,
TouchableNativeFeedback,
TouchableOpacity,
TouchableHighlight
} from 'react-native'
import { DrawerItems, DrawerView } from 'react-navigation';
import Icon from 'react-native-vector-icons/Octicons';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
class DrawerContent extends Component {
constructor(props){
super(props);
console.log('DrawerContent|testtttttt');
}
render(){
return (
<View style={styles.container}>
<Text>Hi darren</Text>
<TouchableOpacity style={{ marginBottom:5 }} onPress={() => this.props.navigation.navigate('RegistrationScreen') } >
<View style={styles.nonIconButton}>
<Text style={{ color: 'black',fontSize: 13 }} >Sign Up</Text>
</View>
</TouchableOpacity>
<Text>Hi darren</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
export default DrawerContent;
First, make sure you are using the latest release of react-navigation as the comment noting that the fix was committed is fairly recent.
Based on your code example, to disable logging for all navigation state changes, you would want to replace this code:
export default StackNavigation;
with:
export default () => (
<StackNavigation onNavigationStateChange={null} />
);
as StackNavigation appears to be your root navigator.
React navigation is great, but this logging is really bad. Solution
const AppNavigator = StackNavigator(SomeAppRouteConfigs);
class App extends React.Component {
render() {
return (
<AppNavigator onNavigationStateChange={null} />
);
}
}

A valid react element(or null) must be returned. You nay have returned undefined,an array or some other invalid object (React Native)

I am trying to compile react native project. the code for the file in which error is :
import React from 'react';
import {Text,View} from 'react-native';
const Header = () =>
{
const {textStyle} =styles;
return
(
<View>
<Text style={textStyle}>Albums!</Text>
</View>
);
};
const styles = {
textStyle:{
fontSize:20
}
};
export default Header;
You're not returning anything, you have to have the open paran on the same line as the return statement.
return (
<View>
<Text style={textStyle}>Albums!</Text>
</View>
);
You can also refactor it to:
import React from 'react';
import {Text,View} from 'react-native';
const {textStyle} =styles;
const Header = () => (
<View>
<Text style={textStyle}>Albums!</Text>
</View>
)
const styles = {
textStyle:{
fontSize:20
}
};
export default Header;