loop and get all TextInput value in a component/screen - react-native

I know that the practice of react native is to use onChangeText for change value as follow.
<TextInput
onChangeText = {(text)=> this.setState({myText: text})}
value = {this.state.myText}
/>
However, I wonder if i could do something like this. To summarise, I want to loop through all the TextInput and get the ref and value. I just want to do things in javascript way as follow. Is that possible to be done?
<TextInput id="id1" ref={ref => (this.remark = ref)} />
<TextInput id="id2" ref={ref => (this.remark1 = ref)} />
onSubmit = () => {
forEach(TextInput in component) {
console.log(TextInput.id) <- note id is custom property
console.log(TextInput.refName)
console.log(TextInput.value)
}
}

Yes, but I wouldn't recommend this approach. You could simply create an array of refs and loop through it in your onSubmit function.

forEach(TextInput in component) {
This is not possible in any javascript environment (not only because forEach and for..in syntax is different but also you can't expect to be able to loop over component elements by type (?) and get them)
What you want to do is not javascript way but old style browser way:
there are no ids in react-native
technically you could get uncontrolled TextInput's value like you would do in plain react in browser environment (via this.textInputRef._lastNativeText) but it's discouraged in react-native, most likely because because instead of DOM react native has to render to native views which all differ depending on the platform (iOS, Android, Windows, etc) but have to work the same
So it's not only impossible in react native but in plain react as well. It looks to me like you want to create a form, and sooner or later you will find out that you want validation or transformation on your inputs and switch back to controlled components anyway

Related

How to determine mouse events in React Native (mobile)?

I need to use a callback function for the mouse click event. Below code is working in React web app:
const checkAnswer = (e: React.MouseEvent<HTMLButtonElement>) => {
const answer = e.currentTarget.value // here .value property is undefined and gives error in React-Native. Just e.currentTarget is defined.
const correct = questions[number].correct_answer === answer
if(correct) setScore(prev => prev + 1)
}
But I couldn't apply it on React Native (mobile) for Pressable or TouchableOpacity.
This is the render part of React web app's code:
<button value={answer} onClick{checkAnswer} />
and I try to apply it on React Native. The value will be passed to button's value. But there is no "value" option in native's Pressable component. Therefore I am confused
Any help?
you can determine touch events by following
<View onTouchStart={(e) => {console.log('touchMove',e.nativeEvent)}} />
Here is some similar scenario what I could able to understand from the question.
There is a Score state which will store the user's score of a quiz game.
There is a array of question where all the options and correct option are given.
There will be a button for the option, if user choose a option, and based on that it will validate if user is correct or not.
It might not be the exact scenario of you. But this could definitely help to solve your scenario.
Here is a solution for the scenario => solution.
If you click on the solution link you will be redirect to a page which is similar to the screenshot attached below. On very right you will find "My Device", "Android", "ios", choose any and run. Run via "my device" with expo app installed in your mobile if you don't want to be in queue for some certain time.
Note: from your code this is for React web:
<button value={answer} onClick{checkAnswer} />
but in React Native you have to use a click event like this:
<TouchableOpacity onPress={()=>buttonHandler()}></TouchableOpacity>
Here ()=> and () extra need to be added to work a function properly.
Also instead of .map() function you can use FlatList to improve your app. FlatList support lazy loading.

Render FlatList of Videos in a performant way

I am using a react native with expo. I have a lot of videos that I need to render (sort of like TikTok does). When I fetch about 30 videos and put them in the flat list in the renderItem method, it gets stuck and luggish. I was thinking about getting an amount of videos but sending to the renderItem method only 3 videos each time, and when the user will scroll down and reach index 2 it will shift the first index and append the fourth video from the fetched one. The idea was to have a small array of size 3 and change the items in it every scroll, in order to prevent rendering all the videos at once. That required array manipulation and caused a rerender each time the array of videos was updated(each change made sort of a flash - what was indicating a whole rerender).
My question is how should it be implemented in order the transition between the videos to be as fast and clean as possible from the client side perspective? What is the correct way to render videos in a flat list so it won't be stuck? I dont think It should be done that way, there has to be a better way.
This is what I have tried:
// challenges is an array coming from a fetch, just sliced it for the purpose of the example
// suppose it is an array that contains 30 items
const [currentVideos, setCurrentVideos] = useState([challenges.slice(0,3)]);
<FlatList
data={currentVideos}
renderItem={renderItem}
keyExtractor={(challenge, i) => challenge._id}
showsVerticalScrollIndicator={false}
snapToInterval={Dimensions.get("window").height - UIConsts.bottomNavbarHeight}
snapToAlignment={"start"}
decelerationRate={"fast"}
ref={(ref) => {
flatListRef.current = ref;
}}
onScrollToIndexFailed={() => alert("no such index")}
onViewableItemsChanged={onViewRef.current}
onScrollEndDrag={() => (scrollEnded.current = true)}
onScrollBeginDrag={beginDarg}
></FlatList>
useEffect(() => {
// just wanted to check on 3 videos
if (currentlyPlaying === 2) {
let temp = currentVideos;
temp.shift(); // pop the top item
temp.push(challenges[4]) // append a new one
setCurrentVideos(temp);
}
}, [currentlyPlaying]);
const onViewRef = useRef(({ viewableItems }) => {
// change playing video only after user stop dragging
scrollEnded.current && setCurrentlyPlaying(viewableItems[0]?.index);
});
I would avoid manipulating the data array and doing business logic inside of the component.
Besides, you can achieve your desired behaviour without the need to manipulate your data array at all, with the maxToRenderPerBatch FlatList prop. As mentioned in the official RN docs for FlatList optimization techniques.
You should avoid using anonymous functions and objects inside of your component's properties, move them outside of the return statement and use the useMemo and useCallback hooks to avoid their unnecessary recreation on every re-render. For example instead of writing your code like this:
const App = () => {
return (
<FlatList
keyExtractor={(challenge, i) => challenge._id}
snapToInterval={Dimensions.get('window').height - UIConsts.bottomNavbarHeight}
/>
);
};
A better approach would be to re-write it to something like this:
const App = () => {
// Because of useCallback, the keyExtractor function will be memoized and won't recreate itself on every re-render
const keyExtractor = useCallback((challenge, i) => challenge._id, []);
// useMemo is almost the same as useCallback, but it is used to return non-function types
// Defining your snapToInterval variable like this will cause it to memoize its value and it
// won't recreate itself on every re-render
const snapToInterval = useMemo(() => Dimensions.get('window').height - UIConsts.bottomNavbarHeight, []);
return (
<FlatList
keyExtractor={keyExtractor}
snapToInterval={snapToInterval}
/>
);
};
If you haven't already, you should consider extracting the component returned from the renderItem function to a different file and applying React.memo to it.
Note: try not to overuse useCallback and useMemo. You can find good and detailed explanation of why not to overuse them here and here.
If you're able to, you should optimize your videos before uploading them to the server. You can optimize your client side part of the app as much as you want, but if the content isn't properly optimized, you won't be able to achieve a smooth and performant experience regardless of your efforts.
Here's also some articles describing how you can optimize your FlatList component:
How did I optimize my React Native FlatList?
8 ways to optimize React native FlatList performance
Optimizing a React Native FlatList With Many Child Components
React Native Performance Optimisation With Hooks
React Native: Optimized FlatList of videos
I hope that some of this will be helpful to you. Good luck.
I have been searching for a solution as well. I have worked out a solution based on some previous work using InViewPort. you can check it out here https://github.com/471Q/React-Native-FlatList-Video-Feed

Add item to list with dynamic icon

When user adds new data to the list I want to add icon dynamically(social icons commonly) in react native. For example,when user adds item that has name facebook then facebook icon should be added in background to the list(item name may be face,fcb etc) How can I achieve this logic ?
Your question is quite vague but I'm guessing you're looking for what's called "conditional rendering".
<View>
{someCondition &&
<FacebookIcon />
}
</View>
The FacebookIcon component will only be rendered if someCondition is true.
So in your case, you probably wanna have a variable that is true or false based on whether your "list" contains the data you want, and use that variable to determine whether to show the icon.
If you want the icon to be dynamic (eg, be able to have Facebook, Insta, Whatsapp), you have another variable that holds the social network you've identified, and pass that as a prop to the icon component:
const listSocialNetwork = 'facebook' // or whatever you find in your list
const showIcon = !!listSocialNetwork // true if a social network was found in the list
// in your render
<View>
{showIcon &&
<SocialIcon socialNetwork={listSocialNetwork} />
}
</View>

ScrollToLocation not working on initial mount

I'd like to add a SectionList to my app such that it renders to a specific section (that isn't the first section in the list). Calling scrollToLocation on componentDidMount does not work; however, adding a button that calls scrollToLocation does. Is there a reason for this?
Could this be due to the SectionList reference (I've tried a few approaches for assigning reference, e.g. variable assignment, function assignment, using createRef, etc.)?
Here is a link to a stripped-down Expo snack to illustrate what I mean: https://snack.expo.io/#bobbymoogs/scrolltolocation-on-componentdidmount.
I found the best solution on this thread is to use onLayout to trigger the scroll:
scrollToInitialPosition = () => {
this.scrollViewRef.scrollTo({ y: 100 });
}
...
<ScrollView
ref={(ref) => { this.scrollViewRef = ref; }}
onLayout={this.scrollToInitialPosition}
/>
Note there are lots of other suggestions using setTimeout, componentDidUpdate, InteractionManager, etc. However using onLayout was the only one that worked for me (and also seems to me to be the cleanest).

How to clear input in SlideTextInput (custom TextInput component)?

and of course sorry if the question is somewhat dumb.
In the app I'm developing a user should be able to swipe on the TextInput. Since TextInput only listens to taps I used this gist: https://gist.github.com/MikeShi42/87b65984f0a31e38d553cc056fcda017
(BTW #Michael Shi thanks a ton)
However, once I changed TextInput to SlideTextInput the Clear button ceased to work.
clearInput() {
this.setState({text: ''});
}
render() {
return (
<Button name='clear' action={this.clearInput} />
<SlideTextInput
style={styles.input}
ref='input'
onChangeText={(text) => this.setState({text: text})}
placeholder={this.state.placeholder}
value={this.state.text}
multiline={true}
returnKeyType='done'
blurOnSubmit={true} />
)
}
I also tried this.refs.input.setNativeProps({text: ''}); instead of just passing a new value prop (that should be — and was — sufficient for normal TextInput), and calling forceUpdate(), but again to no avail. I don't see much changes in SlideTextInput.js compared to the original TextInput component, but I must be missing something that would explain such bad behaviour?
UPD: the answer was pretty simple in the end. Instead of linking the component to its native counterpart (ref={this._setNativeRef}) like original TextInput does, SlideTextInput has it ref'ed to a string (ref="input"). I changed it back and voila.
Looking at the code it seems that the value props is not being sent to the original TextInput. It is extending the TextInput but it is returning another component without sending the value prop.
Try:
this.refs.input.setText('');
The answer was pretty simple in the end. Instead of linking the component to its native counterpart (ref={this._setNativeRef}) like original TextInput does, SlideTextInput has it ref'ed to a string (ref="input") (it's not about props in my code it's about SlideTextInput.js file itself). I changed it back and voila.