how to count views in react native flatlist items - react-native

I have a flat list and it contains a list of posts and videos, now I need to count the views for each item, I tried using viewabilityConfig and onViewableItemsChanged in the flat list and it works fine if I only want to count visible item as a view.
problem is that I had a function written inside onViewableItemsChanged for pausing video right after user scrolls from video.
now I have two functions with different execution times. how can I handle these two functions ?
onViewableItemsChanged = (info) => {
if (this.props.enableView) {
console.log('item viewed after minimumViewavlitytime 5s: ', info) //done after 5s of view time
}
this.pauseVideoFunction(); //done exactly after scrolling
};
viewabilityConfig = {
minimumViewTime:5000,
waitForInteraction: false,
viewAreaCoveragePercentThreshold: 95,
}

i handled it this way:
removed minimumViewTime from config file
added this to constructor since its a class component
this.debouncedViewCount = debounce(this.countView, 5000);*
called debouncedViewCount inside onViewableItemsChanged
now I have a denounced view counter which runs after 5 second if scroll doesn't move and can pause video right after scrolling
class ComponentA extends React.Component {
constructor(props) {
super(props);
this.debouncedViewCount = debounce(this.countView, 5000); //aaaaaaaaaaa
}
countView = (info) => {
debounce(console.log('Debouced 5s', info), 5000, false)
}
onVideoExitScreen = (info) => { //todo working on view aaaaaaaaaaaaaaaaaaaa
if (this.props.enableView) {
this.debouncedViewCount(info);
}
pauseVideoFunction();
};
}
//inside Flatlist
onViewableItemsChanged={this.onViewableItemsChanged}

Related

How to attach an event handler to a dynamically created item in React native

I have created the component array using the list.push, now each item in a view has a button, now the problem is when there is a more components (50-100), when I click to that button, the app hangs for a while.
I have tried the following :
if(!Object.prototype.hasOwnProperty.call(this.clickHandlers, index))
{
this.clickHandlers[index] = () =>
this.props.btnCheckOutAction(this.props.currentState.isModelOpen);
}
return this.clickHandlers[index];
handleItemClick(key) {
debugger
console.log("index::::::::::::::::::::::", key);
if (!Object.prototype.hasOwnProperty.call(this.clickHandlers, index)) {
this.clickHandlers[index] = () => this.props.btnCheckOutAction(this.props.currentState.isModelOpen);
}
return this.clickHandlers[index];
}
When I click to the button of the individual the render call the number of times the list has a component.

React Native - SectionList scroll to end when list is loaded first time

I am working on a chat application.
I am using SectionList to render messages.
I want to scroll to bottom when list loaded.
All messages are of dynamic size so there is no possibility to use getItemLayout.
If I call scrollToLocation immediately, SectionList throws error that scrollToLocation should be used in conjunction with getItemLayout.
How can I achieve this?
loadNextPage() {
var dataSource = this.message_list.load_next_page()
this.setState({ data : dataSource,
isLoading:false,
isPullToRefreshing:false})
}
onMessagesReceived() {
this.loadNextPage()
this.scrollToEnd()
}
scrollToEnd(animated) {
var length = this.state.data.length
if(length > 0) {
setTimeout(()=> {
this.refs.chatList.scrollToLocation({animated:animated,
sectionIndex:length-1,
itemIndex:this.state.
data[length-1].data.length-1,
viewPosition:1})
}, 10)
}
}

Can I use multiple or nested elements in the Label of a Picker Item in React Native?

I'm using React Native with NativeBase and would like to make the labels of my Picker more complicated than just one plain string of text.
But is it even possible to pass elements as the label, say multiple child elements wrapped in a single top-level element?
Or do Pickers only support plain text as labels?
As requested by bennygenel, here's a version of what I've tried:
export default class ThingPicker extends React.Component {
render() {
const {
initialThing,
things,
onThingChanged,
} = this.props;
const orderedThings = things.sort();
return (
<Picker
selectedValue={initialThing}
onValueChange={onThingChanged}>
{buildThingItems(orderedThings)}
</Picker>
);
}
}
function buildThingItems(orderedThings) {
let items = orderedThings.map(th => {
const it = th === "BMD" ? (<Text key={th} label={"foo"} value={"bar"}}>Hello</Text>)
: (<Picker.Item key={th} label={th} value={th} />);
return it;
});
}
Yes! It is possible, it just might not look very "right" for React/JSX code. Just create the elements you need and assign them to the label field:
function buildThingItems(orderedThings) {
let items = orderedThings.map(th => {
const it = (<Picker.Item
key={th}
label={currency === "BMD" ? (<Text>Hello</Text>) : th}
value={th} />);
return it;
});
}

How to programmatically switch a switch in React Native?

I make us several Switch Components in one view. When I switch on one switch, I want all others to switch off. Currently, I set the boolean value property via the state. This results in changes happen abruptly because the switch is just re-rendered and not transitioned.
So how would you switch them programmatically?
EDIT 2: I just discovered that it runs smoothly on Android so it looks like an iOS-specific problem.
EDIT: part of the code
_onSwitch = (id, switched) => {
let newFilter = { status: null };
if (!switched) {
newFilter = { status: id };
}
this.props.changeFilter(newFilter); // calls the action creator
};
_renderItem = ({ item }) => {
const switched = this.props.currentFilter === item.id; // the state mapped to a prop
return (
<ListItem
switchButton
switched={switched}
onSwitch={() => this._onSwitch(item.id, switched)}
/>
);
};

move the view up when keyboard as shown in react-native

hai i am trying to move the view up when keyboard as shown using react-native,I followed the #sherlock's comment in (How to auto-slide the window out from behind keyboard when TextInput has focus? i got an error like this
I don't know how to resolve this error, can any one help me how to resolve this, any help much appreciated.
There's a great discussion about this in the react-native github issues
https://github.com/facebook/react-native/issues/3195#issuecomment-147427391
I'd start there, but here are a couple more links you may find useful, one of which is mentioned already in the article you referenced...
[React Tips] Responding to the keyboard with React Native
Andr3wHur5t/react-native-keyboard-spacer
In my library "react-native-form-generator" (https://github.com/MichaelCereda/react-native-form-generator) i did the following.
I created a Keyboard Aware scroll view (partially modified from https://github.com/facebook/react-native/issues/3195#issuecomment-146518331)
the following it's just an excerpt
export class KeyboardAwareScrollView extends React.Component {
constructor (props) {
super(props)
this.state = {
keyboardSpace: 0,
}
this.updateKeyboardSpace = this.updateKeyboardSpace.bind(this)
this.resetKeyboardSpace = this.resetKeyboardSpace.bind(this)
}
updateKeyboardSpace (frames) {
let coordinatesHeight = frames.endCoordinates.height;
const keyboardSpace = (this.props.viewIsInsideTabBar) ? coordinatesHeight - 49 : coordinatesHeight
this.setState({
keyboardSpace: keyboardSpace,
})
}
resetKeyboardSpace () {
this.setState({
keyboardSpace: 0,
})
}
componentDidMount () {
// Keyboard events
DeviceEventEmitter.addListener('keyboardWillShow', this.updateKeyboardSpace)
DeviceEventEmitter.addListener('keyboardWillHide', this.resetKeyboardSpace)
}
componentWillUnmount () {
DeviceEventEmitter.removeAllListeners('keyboardWillShow')
DeviceEventEmitter.removeAllListeners('keyboardWillHide')
}
scrollToFocusedInput (event, reactNode, extraHeight = 69) {
const scrollView = this.refs.keyboardScrollView.getScrollResponder();
setTimeout(() => {
scrollView.scrollResponderScrollNativeHandleToKeyboard(
reactNode, extraHeight, true
)
}, 220)
}
render () {
return (
<ScrollView
ref='keyboardScrollView'
keyboardDismissMode='interactive'
contentInset={{bottom: this.state.keyboardSpace}}
showsVerticalScrollIndicator={true}
style={this.props.style}>
{this.props.children}
</ScrollView>
)
}
Then i use it like any other scrollview
import { KeyboardAwareScrollView } from 'react-native-form-generator'
...
handleFormFocus(event, reactNode){
this.refs.scroll.scrollToFocusedInput(event, reactNode)
}
...
<KeyboardAwareScrollView ref='scroll'>
<Form ref='registrationForm'
onFocus={this.handleFormFocus.bind(this)}
onChange={this.handleFormChange.bind(this)}
label="Personal Information">
........
</Form>
</KeyboardAwareScrollView>
on change my component (Form) will call scrollToFocusedInput in KeyboardAwareScrollView (using the ref).
i suggest to check the code of my library (see the link on top), or simply use it (everything it's already tested and working).
If you have further questions just comment