RGB function in react - react-native

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.

Related

switch color (from light to dark gradient and vice versa) inside Linear Gradient React Native

I am implementing an UI using Linear Gradient with light gradient background.
I want to make a switch via which i can change the color of Linear Gradient to dark gradient.
any way to do it. I am new in React Native.
Hope i will get my answer soon. Thanks in advance.
You will have to get the current theme and accordingly apply the colors, you can use if ternaries if you need to. Here is the documentation.
import React from "react";
import LinearGradient from "react-native-linear-gradient";
const colorScheme = Appearance.getColorScheme();
const DARK_COLORS = ["#4c669f", "#3b5998", "#192f6a"];
const LIGHT_COLORS = ["#0077c2", "#00a1ff", "#00c2ff"];
const Home = () => {
return (
<LinearGradient
colors={colorScheme === "light" ? LIGHT_COLORS : DARK_COLORS}
>
// Your Content Here
</LinearGradient>
);
};
export default Home;
Here I gave a small example of how I would be using this library, but I believe that this will make it clearer for you on how to apply it in your application.
Until later!

Component Exception (undefined is not an object (evaluating 'list.todos.filter')

I am working on my first React app - everything has been going great but all of a sudden I started getting the error mentioned above. I am not aware of making any changes to my code and therefore for me as an absolute beginner, it is very hard to spot the error. I have been trying to fix the code for two days already and am considering starting over. All I know is that filter seems to be the problem but I cannot really see anything wrong with it. I tried looking for the answer but nothing I found really helped me solve it.
error
And this is my code:
import React from "react";
import { StyleSheet, Text, View, TouchableOpacity, Modal } from "react-native";
import colors from "../colors";
import TodoModal from "./TodoModal";
export default class TaskList extends React.Component {
state = {
showListVisible: false,
};
toggleListModal() {
this.setState({ showListVisible: !this.state.showListVisible });
}
render() {
const list = this.props.list;
const completedCount = list.todos.filter(todo => todo.completed).length;
const remainingCount = list.todos.length - completedCount;
my guess is that during the initial render, this.props.list is null. all you have to do is have a line of code to guard against that.
render() {
const list = this.props.list;
if (!list) return null; // or return some sort of loading element
const completedCount = list.todos.filter(todo => todo.completed).length;
const remainingCount = list.todos.length - completedCount;

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)

ReactNative scrollToEnd() on FlatList - Functional Component

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})

how to disable YellowBox in react-native totally in a native way ? not in JavaScript

I know console.disableYellowBox = true could be answer. But I want ban it with all my control because my App has multiple package and I do not want to use console.disableYellowBox = true in every package.
is there any way to achieve this by set a config in shaking bar ?
I tried with the new React version replacing the import to:
import { LogBox } from "react-native";
and adding this line inside App.js
LogBox.ignoreAllLogs();
And it's working good for me.
You have multiple way's in doing that, which is not recommended since you want to know what's causing these warnings and sometimes it's important informations you need to know, here is some of the ways you can do
Warnings will be displayed on screen with a yellow background. These
alerts are known as YellowBoxes. Click on the alerts to show more
information or to dismiss them.
As with a RedBox, you can use console.warn() to trigger a YellowBox.
YellowBoxes can be disabled during development by using
console.disableYellowBox = true;
using ignore
console.ignoredYellowBox = ['Warning: Each', 'Warning: Failed'];
ignoredYellowBox allows you to ignore certain warnings as you can see in the example above.
using disableYellowBox
console.disableYellowBox = true;
disableYellowBox allows you to disable it completely from your app.
however both these ways you need to use inside App.js before you render you app.
example:
import React, { Component } from "react";
import { View } from "react-native";
//console.disableYellowBox = true;
//OR
//console.ignoredYellowBox = ['Warning: Each', 'Warning: Failed'];
export default class App extends Component {
render() {
return (
<View>
{/*Your Code will be here*/}
</View>
);
}
}
Take a look at Debugging React Native to learn more about YellowBox
// RN >= 0.52
import {YellowBox} from 'react-native';
YellowBox.ignoreWarnings(['Warning: ReactNative.createElement']);
// RN < 0.52
console.ignoredYellowBox = ['Warning: ReactNative.createElement'];