Invalid Hook Call - React Native - react-native

So, I'm trying to use Hooks in React Native but I'm very new to React Native and I don't know how to properly use Hooks in Class and Function components. But in this project, I'm using the Class component but I'm getting an error of invalid hook call, so how do I turn this hook for the function component into the class component.
This is my code:
export default class Home extends Component {
render() {
let [fontsLoaded, error] = useFonts({
Raleway_100Thin,
Raleway_100Thin_Italic,
Raleway_200ExtraLight,
Raleway_200ExtraLight_Italic,
Raleway_300Light,
Raleway_300Light_Italic,
Raleway_400Regular,
Raleway_400Regular_Italic,
Raleway_500Medium,
Raleway_500Medium_Italic,
Raleway_600SemiBold,
Raleway_600SemiBold_Italic,
Raleway_700Bold,
Raleway_700Bold_Italic,
Raleway_800ExtraBold,
Raleway_800ExtraBold_Italic,
Raleway_900Black,
Raleway_900Black_Italic,
});
if (!fontsLoaded) {
return <AppLoading />;
}
return (
<View style={styles.container}>
{/* TITLE */}
<Text style={styles.title}>MALIGAYANG PAGDATING!</Text>
<Text style={styles.subtitle}>RECENTLY VIEWED</Text>
</View>
);
}
}

You can't use hooks inside of a class component. See the Hooks FAQ on the React documentation.

Use this way like
import React from 'react';
import { View, Text } from 'react-native';
import AppLoading from 'expo-app-loading';
import { useFonts, Inter_900Black } from '#expo-google-fonts/inter';
export default function App() {
let [fontsLoaded] = useFonts({
Inter_900Black,
});
if (!fontsLoaded) {
return <AppLoading />;
}
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ fontFamily: 'Inter_900Black', fontSize: 40 }}>Inter Black</Text>
</View>
);
}
Details Here also you can try this way too Here

You cannot use hooks inside a class component. Hooks was designed for functional component only. You can modify your class based component to functional based like below and use it.
// Imports
function Home() {
const [fontsLoaded, error] = useFonts({
Raleway_100Thin,
Raleway_100Thin_Italic,
Raleway_200ExtraLight,
Raleway_200ExtraLight_Italic,
Raleway_300Light,
Raleway_300Light_Italic,
Raleway_400Regular,
Raleway_400Regular_Italic,
Raleway_500Medium,
Raleway_500Medium_Italic,
Raleway_600SemiBold,
Raleway_600SemiBold_Italic,
Raleway_700Bold,
Raleway_700Bold_Italic,
Raleway_800ExtraBold,
Raleway_800ExtraBold_Italic,
Raleway_900Black,
Raleway_900Black_Italic,
});
return fontsLoaded ? (
<View style={styles.container}>
{/* TITLE */}
<Text style={styles.title}>MALIGAYANG PAGDATING!</Text>
<Text style={styles.subtitle}>RECENTLY VIEWED</Text>
</View>
) : (
<AppLoading />
);
}
export default Home;

Related

React Native take useState in class Error: Minified React error #321

I am newbie to react native and
I would like to create a simple app.
using method function to create a TextInput
and make TextInput intergrate to Class export default class App extends React.Component
But unfortunately, I get Error: Minified React error #321, any idea how to make it???
Thank you very much
Full code:
import React, { useState } from 'react';
import { TextInput, Text, View, StyleSheet } from 'react-native';
function Example() {
const [text, setText] = useState('')
return (
<View>
<TextInput
value={text}
style={{ fontSize: 42, color: 'steelblue' }}
placeholder="Type here..."
onChangeText={(text) => {
setText(text)
}}
/>
<Text style={{ fontSize: 24 }}>
{'\n'}You entered: {text}
</Text>
</View>
)
}
export default class App extends React.Component{
render(){
return (
<View>
{Example()}
</View>
);
}
}
You need to call React component like this: <Example />
Here is your code in codesandbox

Styling custom component in react native

I am trying to add styling to my custom component in react native, but no matter what I do, the style has no effect. Here is my code:
// App.js
import MyCustomComponent from './components/myCustomComponent.js';
render() {
return (
<View style={styles.container}>
<MyCustomComponent style={{marginTop: 10}}/>
</View>
);
}
The project compiles fine, and my custom component appears on screen fine, but the marginTop styling is not applied. It is worth noting that the style for the parent View component does apply correctly. This is a brand new project I just created today. This seems like it should be extremely basic, but just isn't working. What can I do to apply this styling?
Custom component code:
import React, {Component} from 'react';
import {TextInput, StyleSheet, Image, View, Button} from 'react-native';
type Props = {};
export default class MyCustomComponent extends Component<Props> {
render() {
return (
<View style={styles.container}>
<Image
source={{ uri: "source here" }}
style={{ width: 50, height: 50 }}
/>
<TextInput
style={{ height: 50 }}
placeholder="Search"
/>
</View>
)
}
}
you can use this code:
export default class MyCustomComponent extends Component<Props> {
render() {
return (
<View style={[styles.container, {...this.props.style}]}>
...
</View>
)
}
}
now, styles.container is applied and anything you pass to component through style will be added to component style.
I hope this can help you
You can apply a style to your custom component by passing style as props.
and
Use it as style={this.props.style} in your MyCustomComponent.
import React, {Component} from 'react';
import {TextInput, StyleSheet, Image, View, Button} from 'react-native';
type Props = {};
export default class MyCustomComponent extends Component<Props> {
render() {
return (
<View style={[styles.container,{...this.props.style}]}>//<--Use like this---
<Image
source={{ uri: "source here" }}
style={{ width: 50, height: 50 }}
/>
<TextInput
style={{ height: 50 }}
placeholder="Search"
/>
</View>
)
}
}
add this code in your CustomText.js file (custom component):
import React from 'react'
import {Text, StyleSheet} from 'react-native'
const CustomText = props => {
return (<Text {...props} style={{...styles.text, ...props.style}}>{props.children}</Text>);
}
export default CustomText;
const styles = StyleSheet.create({
text:{
color: '#000'
}
})
and use in the file:
<CustomText style={styles.text}>My text</CustomText>
const styles = StyleSheet.create({
text:{
fontSize: 20,
}
});
this code merge styles and pass all property to the custom components.
For example, lets change background color of custom card.
Custom Card:
export default function MyCard({color}) {
return (
<View style={[styles.card, {backgroundColor: color}]}>
</View>
)
}
In another file
<MyCard color={"pink"} />
Here, styles.card is the style added in Custom Card file and the color is given during component use.
Note: MyCard({color}) if you miss to add highlight parentheses, it will not work. I faced this issue.
You need to apply this style yourself inside MyCystomComponent. For example:
const MyCustomComponent = ({style}) => (
<View style={style}> // This will be the style that is passed as a prop.
</View>
);

Update an input field in the webview from react-native component

I have a webview component like this:
export default class Home extends React.Component {
onMessage(m) {
//Update an input field in the webview with a custom value
}
render(){
let jsCode = '';
return (
<WebView
ref={(webView) => { this.webView.ref = webView; }}
injectedJavaScript={jsCode}
url={this.state.url}
onMessage={m => this.onMessage(m)}
/>
)
}
}
The webpage has an input field with an id='inpOne'. onMessage prop is triggered by a button click inside the webpage. How to update the input field with the above id when the onMessage prop is executed?
Stripped most of the code for brevity.
Probably like this.
export default class Home extends React.Component {
onMessage(m) {
const js = `document.getElementById('inpOne').value = ${m};`
this.webView.injectJavaScript(js);
}
}
Also, check your WebView's ref prop definition. It looks incorrect. Should be ref={ref => (this.webView = ref)}
Here is the full code of how to change HTML inside of WebWiew from React Native
import React, { Component } from 'react';
import { Text, View, TouchableHighlight } from 'react-native';
import { WebView } from 'react-native-webview';
export default class Sample extends Component {
constructor(props) {
super(props);
}
sendDataFromReactNativeToWebView() {
let injectedData = `document.getElementById("login_field").value = 'xyz#github.com';`;
this.webView.injectJavaScript(injectedData);
}
render() {
return (
<View style={{ flex: 1, marginTop: 30 }}>
<TouchableHighlight style={{ padding: 10, backgroundColor: 'gray', marginTop: 20 }} onPress={() => this.sendDataFromReactNativeToWebView()}>
<Text style={{ color: 'white' }}>Send Data To WebView from React Native</Text>
</TouchableHighlight>
<WebView
style={{ flex: 1 }}
source={{ uri: 'https://github.com/login' }}
ref={(webView) => this.webView = webView}
/>
</View>
);
}
}

Adding a View By Clicking a Button- REACT NATIVE

How can I add a view to the bottom of the screen with the click of a button, which is at the top of the screen, in React Native?
you make the view at the bottom of the screen conditionally render based on a state and you set it that state to be true on the OnPress method of the button
I think it is better to learn more about state and props and other fundamental concepts in react/react-native first:
https://facebook.github.io/react-vr/docs/components-props-and-state.html
but here is how you can do this:
You need to define a state if you can view that section as
false
, then when the button pressed, change the value of that state to
true
import React from 'react';
import {Text,View,TouchableOpacity} from 'react-native';
export default class testComponent extends React.Component {
constructor(){
super()
this.state = {
viewSection :false
}
}
renderBottomComponent(){
if(this.state.viewSection) {
return (
<View>
<Text>Hi!</Text>
</View>
)
}
}
buttonPress=()=>{
this.setState({viewSection:true})
}
render() {
return (
<View >
<TouchableOpacity onPress={this.buttonPress}>
<Text> Click Me!</Text>
</TouchableOpacity>
{this.renderBottomComponent()}
</View>
);
}
}
You can try this,
According to my knowledge this is what you want
import React, { useState } from 'react';
import { Button, View } from 'react-native';
export default function Testing() {
const Square = () => (
<View style={{
width: 50,
height: 50,
margin: 10,
backgroundColor: "green",
}} />
);
const [squares, setSquares] = useState([<Square />, <Square />, <Square />]);
return (
<View >
{squares.map(v => v)}
<Button title='add' onPress={() => setSquares([...squares, <Square />])} />
</View >
)
}

Unexpected token, expected; When calling a function in react native

I am trying to call a function when a button is pressed.
After I add the function, it errors out with the Unexpected token error.
I followed instructions from all previous similar questions but it doesn't solve my case. Please help.
_handlePress: function() {
console.log("Butto GO!")
}
export default class fun extends Component {
render() {
return (
<View style={styles.container}>
<TouchableHighlight onPress={() => this._handlePress()}>
<Image style={{width: 50, height: 50}} source={require('./go.png')} />
</TouchableHighlight>
</View>
);
}
}
Also, Should the called function be defined before the default class?
Put the function behind render, after the class and I don't know if u do test : function() it works there so try my example and give feedback
export default class fun extends Component {
_handlePress() {
console.log("Butto GO!")
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight onPress={() => this._handlePress()}>
<Image style={{width: 50, height: 50}} source={require('./go.png')} />
</TouchableHighlight>
</View>
);
}
}
or if you want to do behind the export class you can use _handlePress() instead of this._handlePress() and it should work!
Example:
'use strict';
import React, {Component} from 'react';
import {View,Text,TouchableOpacity,Alert,Dimensions} from 'react-native';
const windows = Dimensions.get('window');
export default class Feed extends Component {
_test(){
Alert.alert("Test");
console.log("It worked!");
}
render() {
return (
<View style={{flex: 1}}>
<TouchableOpacity onPress={() => this._test()}>
<Image source={require('../image/2.jpg')} style={{height: windows.height, width: windows.width, }} />
</TouchableOpacity>
</View>
);
}
}