ReactNative scrollToEnd() on FlatList - Functional Component - react-native

Am trying to implement a chat app using ReactNative. The problem am facing is, after new item is added to the FlatList, am trying to scroll the FlatList items to the bottom so that the newly added message is visible.
When I checked the documentation, I can see a method called scrollToEnd(). But not sure how to use it as am following the Functional Component style of coding. Because when I googled, I can see examples where it uses the ref in a Class Component style coding.
But couldn't find how to use it in Functional Component!

I think you're looking for useRef
// I hope you don't mind the typescript
import {useRef} from 'react';
import {FlatList} from 'react-native';
export const Comp = () => {
const flatListRef = useRef<FlatList<any>>();
// however you detect new items
flatListRef?.current?.scrollToEnd();
return (
<FlatList
data={[]}
renderItem={() => null}
ref={flatListRef}
/>
);
}
But I think if you use inverted={true} on the flat list, it should snap to the top, or better bottom (I think).

For typescript you can use just:
const listRef = useRef<FlatList>(null);
and in your code you just need to check if your ref is exist:
listRef?.current?.scrollToIndex({animated: true, index: yourIndex})

Related

how to change element that fits a component to an element that fits a function in react native

I am a new react native developer, I found a component and I want to use it in a function, but it is not clear to me how I would change it, can I get a help?
Here is the component
import TagInput from 'react-native-tag-input';
...
<TagInput
value={this.state.emails}
onChange={(emails) => this.setState({ emails })}
labelExtractor={(email) => email}
text={this.state.text}
onChangeText={(text) => this.setState({ text })}
/>
I got the code from here https://bestofreactjs.com/repo/jwohlfert23-react-native-tag-input
I guess you are asking how to adapt the code to fit the functional component, which includes converting the this.setState.
React provides some thing called React hooks, which you can think of as a way to replace states and lifecycles. You can read more about it here here
In your case, it would go like this:
import { useState } from 'react';
...
// useState can only be called inside functional components
const [emails, setEmails] = useState([]);
const [text, setText] = useState('');
...
<TagInput
value={emails}
onChange={(emailTags) => setEmails(emailTags)} // to avoid naming confusion
labelExtractor={(email) => email}
text={text}
onChangeText={(inputText) => setText(inputText)}
/>
you don't need to convert the component itself, you can use it as it is, but you need to change its implementation.
Basically, if you want to use function components, which is highly recommended now, you need to change the usage of the state in the component which will contain the <TagInput>.
Instead of using "this" which points to the class itself, you need to implement a hook called useState.
You can find it the docs here: https://reactjs.org/docs/hooks-state.html

FontAwesome react-native warnings

i am trying to use fontawesome in react-native-web-app
Did everything as suggested in docs, but for some reason getting this warning in console.
<FontAwesomeIcon icon={faSearch} style={[styles.icon]} /> - this is the part which triggers all warnings. If I will remove it , warning are gone too.
Warnings:
Warning: React does not recognize the secondaryFill prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase secondaryfill instead. If you accidentally passed it from a parent component, remove it from the DOM element.
Warning: React does not recognize the secondaryOpacity prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase secondaryopacity instead. If you accidentally passed it from a parent component, remove it from the DOM element.
Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of Path which is inside StrictMode. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node
Warning: findDOMNode is deprecated in StrictMode. findDOMNode was passed an instance of Svg which is inside StrictMode. Instead, add a ref directly to the element you want to reference. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-find-node
It looks like this is a known issue with an open pull request in the library: https://github.com/FortAwesome/react-native-fontawesome/pull/74
For now, the last comment in that thread offers a workaround. You can use #fortawesome/react-fontawesome for web, and react-native-fontawesome for Android/iOS.
Copying their code snippet here:
import {FontAwesomeIcon as FontAwesomeReact} from '#fortawesome/react-fontawesome';
import {FontAwesomeIcon as FontAwesomeNative} from '#fortawesome/react-native-fontawesome';
import {number} from 'prop-types';
import React from 'react';
import {Platform, StyleSheet} from 'react-native';
FaIcon.propTypes = {
size: number,
};
export default function FaIcon({size, style, ...props}) {
if (Platform.OS === 'web') {
const webStyles = StyleSheet.flatten([style, {width: size, height: size}]);
return <FontAwesomeReact {...props} style={webStyles} />;
}
return <FontAwesomeNative {...props} size={size} style={style} />;
}

Query in react native about sliding up panel

In React Native iOS, I would like to slide in and out of a like in the following picture.
So I installed this https://github.com/octopitus/rn-sliding-up-panel for ease.
but this error is showing =>
i cant understand whats wrong, I am new to react native. Please Help!
You cannot access variable called _panel from this object because you are inside a function itself. besides you are using function based react, in order to create a reference check useRef() hook or switch to class based component and then you can use this._panel;
smthg like this:
function AccessingElement() {
const elementRef = useRef();
const onPress = () => {
// e.g
elementRef.current.show();
}
return (
<View ref={elementRef}>
...child views
</View>
);
}

Fetching Data From Server Using iOS Device in React Native

I have just started learning React Native and development for mobile devices. One of the things I've tried is using fetch API to get data from http://jsonplaceholder.typicode.com/posts
The App.js file is given below:
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, Button, TextInput } from 'react-native';
export default function App() {
const [firstLoad, setLoad] = React.useState(true);
const [data, upDateData] = React.useState([]);
let isLoading = true;
async function sampleFunc() {
let response = await fetch("https://jsonplaceholder.typicode.com/posts");
let body = await response.json();
upDateData(body);
}
if (firstLoad) {
sampleFunc();
setLoad(false);
}
if (data.length > 0) isLoading = false;
const posts = data.map(post => (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
));
return (
<View style={styles.container}>
{isLoading ?
<Text>Loading</Text> :
<Text>{posts}</Text>
}
</View>
);
}
Nothing fancy is going on here, just making an https request to the server to get posts. While the data is being transferred, the Loading label is being displayed, after that, all fetched posts are rendered on the page.
I am using Expo, and everything works fine when I run it in the browser, but when I scan the QR code, Expo app opens, the Loading message is displayed for a couple of seconds, and then the app crashes.
I may be doing something here that is typical of regular React and is not used in React Native. It is just strange that it would work on my computer and not the phone. Any suggestions would be greatly appreciated. Thank you in advance!
You cannot have text outside of Text components in react-native.
In your example, in the post function, you use the h1 and p tags, which are not supported by react-native.
The fix here is to make sure that those texts are inside Text components, you can have styling set to those to make them look closer to what you want.
You can refer the docs on how to create custom styles.
const posts = data.map(post => (
<View>
<Text>{post.title}</Text>
<Text>{post.body}</Text>
</View>
));
To debug similar issues in the future, you should be getting a red flashing screen with the exception. (Maybe it doesn't appear when running on Expo)

RGB function in react

I've recently started to work on React Native. I'm trying to create a simple function for generating Random Colors. The problem I am facing is that my IDE says that the variables that I have declared are not in use. Hence, the color is not generated on the my device's screen. Can anyone kindly have a look at it tell me what am I doing wrong?
P.S: I tried setting the color manually in the "View state" by writing "backgroundColor: 'rgb(0,255,0)'}}/>" and it successfully worked. The only time I am facing a problem is when I am trying to use the randomRGB function.
import React from 'react';
import {StyleSheet, Button, View, Text} from 'react-native';
const ColorScreen = () => {
return(
<View style={{height:100 , width:100, backgroundColor:randomRgb()}}/>
}
const randomRgb = () =>{
const red = Math.floor(Math.random()*256);
const green = Math.floor(Math.random()*256);
const blue = Math.floor(Math.random()*256);
return 'rgb(${red}, ${green}, ${blue})';
};
export default ColorScreen;
Nvm guys. I'm an idiot. I was using quote instead of backquotes. Yeah stupid I know, but I wouldn't delete this because there may be other people like me. So, use " ` " instead.