execute hooks inside a function in react native - react-native

Can I use hooks inside a function? For example I have implemented the following code:
import React, { useState, useEffect, Component} from 'react';
export default class App extends Component {
checkdata_db(){
const [booblenavalue,setboolenavalue]=useState(false);
useEffect(() => {
setboolenavalue(true)
}, [])
console.log(booblenavalue);
}
render(){
}
}
This code doesn't work. It throws the following error:
Invalid hooks call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app"
How can i run hooks inside checkdata_db method?

Hey #Elly as #yousoumar said , you cant use hooks in classes , it can be only done with functional comp:
You can convert it to like this :
Also you cant use useEffect,useState inside any conditional statements like if,else etc.
So you need to add useEffect outside any functions etc
import React, { useState, useEffect, Component} from 'react';
const App = () => {
const [booblenavalue,setboolenavalue]=useState(false);
useEffect(() => {
setboolenavalue(true)
}, [])
const checkdata_db = () => {
console.log(booblenavalue);
}
return <View />
}
Hope it helps feel free for doubts

Related

React Native - ExpoPixi : Illegal invocation

im new to use RactNative.
so i want to build web app using RN and use ExpoPixi to build signature.
When i try to import the ExpoPixi, it return error Unhandled Rejection (TypeError): Illegal invocation on Chrome.
this is my component
import React, { useRef } from 'react';
import ExpoPixi from 'expo-pixi';
export const Registration: React.FC<Props> = (props, { text }) => {
let signRef = useRef(null);
return(
<ExpoPixi.Signature
ref={signRef}
strokeWidth={3}
strokeAlpha={0.5}
/>
)
}
is that error related to webpack?
what should i do?

How to use withNavigation in react-navigation v5?

I have a nested component, and I want to use withNavigation in the nested component in react-navigation v5.
why you don't create your own withNavigation
import React from 'react';
import { useNavigation } from '#react-navigation/native'; // not sure package name
export const withNavigation = (Component: any) => {
return (props: any) => {
const navigation = useNavigation();
return <Component navigation={navigation} {...props} />;
};
};
React Navigation Version: 5.x
Sometimes you need to trigger a navigation action from places where you do not have access to the navigation prop, such as a Redux middleware. For such cases, you can dispatch navigation actions from the navigation container.
If you're looking for a way to navigate from inside a component without needing to pass the navigation prop down. Do not use this method when you have access to a navigation prop or useNavigation since it will behave differently, and many helper methods specific to screens won't be available.
You can get access to the root navigation object through a ref and pass it to the RootNavigation which we will later use to navigate.
// App.js
import { NavigationContainer } from '#react-navigation/native';
import { navigationRef } from './RootNavigation';
export default function App() {
return (
<NavigationContainer ref={navigationRef}>{/* ... */}</NavigationContainer>
);
}
In the next step, we define RootNavigation, which is a simple module with functions that dispatch user-defined navigation actions.
// RootNavigation.js
import * as React from 'react';
export const navigationRef = React.createRef();
export function navigate(name, params) {
navigationRef.current?.navigate(name, params);
}
// add other navigation functions that you need and export them
Then, in any of your javascript modules, just import the RootNavigation and call functions that you exported from it. You may use this approach outside of your React components and, in fact, it works just as well when used from within them.
// any js module
import * as RootNavigation from './path/to/RootNavigation.js';
// ...
RootNavigation.navigate('ChatScreen', { userName: 'Lucy' });
Apart from navigate, you can add other navigation actions:
import { StackActions } from '#react-navigation/native';
export function push(...args) {
navigationRef.current?.dispatch(StackActions.push(...args));
}
https://reactnavigation.org/docs/navigating-without-navigation-prop/

React Native | Passing data between components

I am a beginner with React Native. I would like to pass data between two components. I get the following error:
TypeError: undefined is not an object (evaluating 'params.title'
App.js
import React from 'react';
import TabBar from './components/TabBar';
export default function App() {
return (
<TabBar title="Hall Building"/>
);
}
TabBar.js
import React, { useState } from 'react';
import { Text } from 'react-native';
export default function TabBar({ params }){
const [tabContent] = useState([
{
title: params.title,
}
])
return(
<Text>
{ tabContent.title }
</Text>
);
}
export { TabBar };
There are a couple things you're doing wrong in your TabBar component.
In theTabBar you are destructuring the property params but your property is called title. You either have to remove the curly braces or rename it to title. If you rename params to title you can remove params. and simply leave title. If you chose to remove the curly braces you can leave it as it is.
Then you also try to access tabContent.title but tabContent is an array with objects. You either have to remove the square brackets and pass an object as argument to useState OR you can access the title by getting the first index like so tabContent[0].title.
Change your TabBar into this :
import React, { useState } from 'react';
import { Text } from 'react-native';
export default function TabBar({ title }){
const [tabContent] = useState(title)
return(
<Text>
{ tabContent }
</Text>
);
}
export { TabBar };
hope it helps.

Context API w/ React Navigation (React Native)

I'm trying to wrap my mind around using Context in my React Native app that uses React Navigation. I think I am way off on this one. I am simply trying to pass the name of a book to my entire app through the navigation stacks.
App.js
const BookContext = React.createContext();
class BookProvider extends Component {
state = {
name: 'book name'
}
render() {
return (
<BookContext.Provider value={{
name: this.state.name
}}>
{this.props.children}
</BookContext.Provider>
)
}
}
export default function App() {
return (
<BookProvider>
<BookContext.Consumer>
{({ name }) => (<Routes name={name} />)} //my react navigation stacks component
</BookContext.Consumer>
</BookProvider>
);
}
and in Book.js (a component in the navigation stack)
componentDidMount() {
console.log(this.context)
}
returns an empty object {}
Any help is appreciated!
To save you some Googling, this is the correct approach: https://github.com/react-navigation/react-navigation/issues/935#issuecomment-359675855
Another way, if you're using a relatively new version of React, and your component in question at that route is a functional component, is to use the useContext React hook.
e.g.
import React, { useContext } from 'react'
import { BookContext } from '/path/to/BookContext'
function BookConsumerComponent() {
const { name } = useContext(BookContext);
console.log(name);
}

Why is this.props.componentId needed?

Why is this.props.componentId needed?
What is its purpose?
Why can't we use the library without that id being needed?
react-navigation doesn't need something like that, and react-native-navigation v1 didn't use anything like that. So why does v2 needs and uses that? The reason I ask is firstly to understand it, and secondly to see if I can skip this since now I cannot use RNN v2 from a saga.
Here's a detailed answer from a blogpost by the react-native-navigation library developer.
So now we want to enable the following behavior: after user clicks on the text, the app pushes the ViewPost screen. Later on it will be very easy to attach the same function to a list item instead of the text. To push a new screen into this screen’s navigation stack, we will use Navigation.push. In the new API this method expects to receive the current componentId which can be found in props.componentID. So in PostsList.js we create a pushViewPostScreen function and attach it to the onPress event of the Text.
import React, {PureComponent} from 'react';
import {View, Text} from 'react-native-ui-lib';
import PropTypes from 'prop-types';
import {Navigation} from 'react-native-navigation';
class PostsList extends PureComponent {
static propTypes = {
navigator: PropTypes.object,
componentId: PropTypes.string
};
constructor(props) {
super(props);
this.pushViewPostScreen = this.pushViewPostScreen.bind(this);
}
pushViewPostScreen() {
// We pass the componentId to Navigation.push
// to reference the which component will be pushed
// to the navigation stack
Navigation.push(this.props.componentId, {
component: {
name: 'blog.ViewPost',
passProps: {
text: 'Some props that we are passing'
},
options: {
topBar: {
title: {
text: 'Post1'
}
}
}
}
});
}
render() {
return (
<View flex center bg-blue60>
<Text onPress={this.pushViewPostScreen}>Posts List Screen</Text>
</View>
);
}
}
export default PostsList;
In the official docs, it seems that the Screen API, which is responsible of pushing, popping and changing navigation, will be accessible through the Navigation module always expecting a props.componentId to get the reference to the component.