React-native - How to create a scrollable flatList in which the chosen item is the one at the middle? - react-native

I would like to create a scrollable FlatList to select only one item among a list. After the user scroll the list, the selected item will be the one in the colored rectangle (which have a fixed position) as you can see here :
Actually I'm only able to render a basic FlatList even after some researches.
Do you know how I should do that ?

I found the solution (but it's not a FlatList) !
To do that I use :
https://github.com/veizz/react-native-picker-scrollview.
To define the background of the current selected items I added a new props highLightBackgroundColor in the ScrollPicker Class in the index file of react-native-picker-scrollview :
render(){
...
let highLightBackgroundColor = this.props.highLightBackgroundColor || '#FFFFFF';
...
let highlightStyle = {
...
backgroundColor: highLightBackgroundColor,
};
...
How to use it :
<ScrollPicker
ref={sp => {
this.sp = sp;
}}
dataSource={['a', 'b', 'c', 'd', 'e']}
selectedIndex={0}
itemHeight={50}
wrapperHeight={250}
highLightBackgroundColor={'lightgreen'}
renderItem={(data, index, isSelected) => {
return (
<View>
<Text>{data}</Text>
</View>
);
}}
onValueChange={(data, selectedIndex) => {
//
}}
/>
How it looks without others customizations:

You can implement the same setup with the very popular react-native-snap-carousel package, using the vertical prop. No need to use a smaller, poorly documented/unmaintained package for this.

Related

PageView's onPageScroll gives wrong position on iPhone 12+

Using "react-native-pager-view": "^6.1.2" package in ReactNative.
I have the same bug as here.
https://github.com/callstack/react-native-pager-view/issues/503
I'm trying PagerView with the code pasted below, but when I swipe to move the page, e.nativeEvent.position is different from the actual page index.
import PagerView, { PagerViewOnPageScrollEvent, PagerViewOnPageSelectedEvent } from 'react-native-pager-view';
import Modal from 'react-native-modal';
const onPageScroll = useCallback((e: PagerViewOnPageScrollEvent) => onPageScrollPagerView(e, setCurrentTabIndex), []);
const onPageScrollPagerView = (
e: PagerViewOnPageScrollEvent,
setCurrentTabIndex: React.Dispatch<React.SetStateAction<number>>,
) => {
console.log(`onPageScroll position = ${e.nativeEvent.position}`);
setCurrentTabIndex(e.nativeEvent.position);
};
return (
<Modal isVisible={isVisible}>
<SafeAreaView>
<View>
<PagerView ref={viewPager} initialPage={0} onPageScroll={onPageScroll} onPageSelected={onPageSelected}>
      {list.map((item) => (
     <View key={item.id}>
    {item.content}
     </View>
      ))}
        </PagerView>
</View>
</SafeAreaView>
</Modal>
);
This is the result obtained when scrolling to the first page.
onPageScroll is called twice, and for some reason the wrong position is returned the second time.
And 0 is set to setCurrentTabIndex.
onPageScroll position = 1
onPageScroll position = 0
Is there any way to resolve this?
It may be related to what you write in <Modal></Modal> of 'react-native-modal'.
As also written here, this problem does not occur on iPhone11, but on iPhone12 and newer devices.
I didn't use 'react-native-modal', I used fullscreen modal.
screenOptions={{ presentation: 'modal' }}

Populte WYSIWYG editor after react native fetch

I am trying to incorporate this WYSIWYG package into my react native project (0.64.3). I built my project with a managed workflow via Expo (~44.0.0).
The problem I am noticing is that the editor will sometimes render with the text from my database and sometimes render without it.
Here is a snippet of the function that retrieves the information from firebase.
const [note, setNote] = useState("");
const getNote = () => {
const myDoc = doc(db,"/users/" + user.uid + "/Destinations/Trip-" + trip.tripID + '/itinerary/' + date);
getDoc(myDoc)
.then(data => {
setNote(data.data()[date]);
}).catch();
}
The above code and the editor component are nested within a large function
export default function ItineraryScreen({route}) {
// functions
return (
<RichEditor
onChange={newText => {
setNote(newText)
}}
scrollEnabled={false}
ref={text}
initialFocus={false}
placeholder={'What are you planning to do this day?'}
initialContentHTML={note}
/>
)
}
Here is what it should look like with the text rendered (screenshot of simulator):
But this is what I get most of the time (screenshot from physical device):
My assumption is that there is a very slight delay between when the data for the text editor is actually available vs. when the editor is being rendered. I believe my simulator renders correctly because it is able to process the getNote() function faster.
what I have tried is using a setTimeOut function to the display of the parent View but it does not address the issue.
What do you recommend?
I believe I have solved the issue. I needed to parse the response better before assigning a value to note and only show the editor and toolbar once a value was established.
Before firebase gets queried, I assigned a null value to note
const [note, setNote] = useState(null);
Below, I will always assign value to note regardless of the outcome.
if(data.data() !== undefined){
setNote(data.data()[date]);
} else {
setNote("");
}
The last step was to only show the editor once note no longer had a null value.
{
note !== null &&
<RichToolbar
style={{backgroundColor:"white", width:"114%", flex:1, position:"absolute", left:0, zIndex:4, bottom: (toolbarVisible) ? keyboardHeight * 1.11 : 0 , marginBottom:-40, display: toolbarVisible ? "flex" : "none"}}
editor={text}
actions={[ actions.undo, actions.setBold, actions.setItalic, actions.setUnderline,actions.insertLink, actions.insertBulletsList, actions.insertOrderedList, actions.keyboard ]}
iconMap={{ [actions.heading1]: ({tintColor}) => (<Text style={[{color: tintColor}]}>H1</Text>), }}
/>
<RichEditor
disabled={disableEditor}
initialFocus={false}
onChange={ descriptionText => { setNote(descriptionText) }}
scrollEnabled={true}
ref={text}
placeholder={'What are you planning to do?'}
initialContentHTML={note}
/>
}
It is working properly.

Creating a checkbox group with React Native

Good Morning! I am wanting to create a selection box where the user has several options of items to choose from and when clicking on a button, it triggers a function that shows all the values that the user chose in the form of an array, json or even arrays ( hard task).
In the React Native documentation, only simple examples of checkboxes using the component are provided and I wanted to go much further than the documentation provides me. What are the possible solutions to this problem? (from a simpler example to an advanced one) and what (s) ways can I explore this problem in order to solve it in the most practical and uncomplicated way?
Definitions and examples of official documentation:
https://reactnative.dev/docs/checkbox/ (CheckBox)
https://reactnative.dev/docs/button/ (Button)
With this problem, another one came up: build an application where the user selects shopping options (items) and a subtotal is displayed in the lower corner of the application as he selects or deselects the items he is going to buy, and there is also an option to reset the subtotal by returning it to the zero value.
From the problem mentioned at the beginning, what are the possible solutions to create this application previously mentioned in a practical and simple way?
Multi Checkbox example ( Updated with Hook )
export const Example = () => {
const [checkboxes, setCheckboxes] = useState([{
id: 1,
title: 'one',
checked: false,
}, {
id: 2,
title: 'two',
checked: false,
}]);
const onButtonPress = () => {
const selectedCheckBoxes = checkboxes.find((cb) => cb.checked === true);
// selectedCheckBoxes will have checboxes which are selected
}
const toggleCheckbox = (id, index) => {
const checkboxData = [...checkboxes];
checkboxData[index].checked = !checkboxData[index].checked;
setCheckboxes(checkboxData);
}
render(){
const checBoxesView = checkboxes.map((cb, index) => {
return (
<View style={{flexDirection:"row"}}>
<Checkbox
key={cb.id}
checked={cb.checked}
onPress={() => toggleCheckbox(cb.id, index)} />
<Text>{cb.title}</Text>
</View>
);
});
return (
<View>
{ checBoxesView }
<Button onPress={onButtonPress} title="Click" />
</View>
);
}
}

React Native. Filter FlatList - error "index=10 count 0"

My task is to filter some array and set it to FlatList.
My filter function is:
updateInvoiceList = (text) => {
let invoiceList = [...this.state.baseInvoiceList];
invoiceList = invoiceList.filter(el => {
return el.name.toLowerCase().includes(text.toLowerCase())
});
this.setState({invoiceList})
}
After filtering, I provide state.invoiceList to FlatList and everything works correctly. But, when I set some symbol which does not exist in my array, for example "!", the function clears the array and it still behaves correctly. When I remove the symbol "!", I get an error screen with:
index=10 count=0
addInArray
ViewGroup.java:5235
addViewInner
ViewGroup.java:5128
addView
ViewGroup.java:4935
addView
ReactViewGroup.java:452
addView
ViewGroup.java:4875
addView
ReactViewManager.java:269
addView
ReactViewManager.java:36
manageChildren
NativeViewHierarchyManager.java:346
execute
UIViewOperationQueue.java:227
run
UIViewOperationQueue.java:917
flushPendingBatches
UIViewOperationQueue.java:1025
access$2600
UIViewOperationQueue.java:46
doFrameGuarded
UIViewOperationQueue.java:1085
doFrame
GuardedFrameCallback.java:29
doFrame
ReactChoreographer.java:166
doFrame
ChoreographerCompat.java:84
run
Choreographer.java:964
doCallbacks
Choreographer.java:790
doFrame
Choreographer.java:721
run
Choreographer.java:951
handleCallback
Handler.java:883
dispatchMessage
Handler.java:100
loop
Looper.java:214
main
ActivityThread.java:7356
invoke
Method.java
run
RuntimeInit.java:492
main
ZygoteInit.java:930
What did I do wrong?
I had the exact same issue with my code, inside a Flatlist and only showing up on Android. I've managed to solve it as follows:
My FlatList had
stickyHeaderIndices={this.state.items[1]}
but apparently the List was loading that stickyHeader ahead of its initialization. From here, the solution consists simply in handling the case in which that item is not initialized yet.
stickyHeaderIndices={this.state.items.length > 0 ? [1] : [0]}
Hope this helps! The solution is pretty straightforward. Debugging it can be a real pain, tho!
On Android, you must not initialise your FlatList stickyHeaderIndices with empty array.
Instead, when your state is not loaded yet, provide FlatList data with some initial data and provide stickyHeaderIndices with [0]
Example code as below
let [data, stickyIndices] = someAPIToGetYourData()
...
...
...
// if your data is not finished loading yet
if (data.length === 0) {
// create not-empty array
data = getInitialNotEmptyData()
// add not-empty index
headerIndexList = [0]
}
return (
<SafeAreaView>
<FlatList
data={data}
stickyHeaderIndices={headerIndexList /* This must not be empty */ }
renderItem={item => renderYourItem(item)}
/>
</SafeAreaView>
)
Hope this help!
I needed kill the FlatList to fix this error, like this:
<View>
{ this.state.data.length > 0 &&
<FlatList
showsVerticalScrollIndicator={false}
refreshing={false}
onRefresh={() => this.onRefresh()}
data={this.state.data}
extraData={this.state}>}
</View>
Hope this helps!
LayoutAnimation causes a similar issue, not only with Flatlist but any kind of lists, check if you are using it in your app and if you have UIManager.setLayoutAnimationEnabledExperimental(true) on your top component, removing it might fix your issue, but will disable the layoutAnimations.
You might find more information here and here
Please improve your function.
updateInvoiceList = (text) => {
let invoiceList = [];
const { baseInvoiceList } = this.state;
if(text){
invoiceList = baseInvoiceList.filter(item => {
return item.name.toLowerCase().includes(text.toLowerCase());
});
}
this.setState({invoiceList});
}

How to render absoulute element inside ListView or FlatList?

Here's a fun one i've been poking at for while:
I have a FlatList (same issue with ListView) and I want to render an element INSIDE the internal scrolling container with the following characteristics:
Absolutely Positioned (thus having no effect on position of list elements)
Position XX distance from top (translateY or top)
zIndex (above list elements)
The use case is i'm rendering a day view calendar grid with a horizontal bar at the current time position fixed at X distance from the beginning of the internal scrollview so it appears as the user scrolls pass that position.
So far i've tried wrapping wrapping FlatList/ListView with another ScrollView... also tried rendering this element as the header element which only works while the header/footer are visible (trashed when out of view).
Any and all ideas welcomed. :)
Thanks
Screenshot Below (red bar is what i'm trying to render):
Here's a working demo of what it sounds like you're trying to achieve: https://sketch.expo.io/BkreW1che. You can click "preview" to see it in your browser.
And here's the main code you need to measure the height of the ListView and place the indicator on top of it (visit the link above to see the full source):
handleLayout(event) {
const { y, height } = event.nativeEvent.layout;
// Now we know how tall the ListView is; let's put the indicator in the middle.
this.setState({ indicatorOffset: y + (height / 2) });
}
renderIndicator() {
const { indicatorOffset } = this.state;
// Once we know how tall the ListView is, put the indicator on top.
return indicatorOffset ? (
<View style={[{ position: 'absolute', left: 0, right: 0, top: indicatorOffset }]} />
) : null;
}
render() {
return (
<View style={styles.container}>
<ListView
onLayout={(event) => this.handleLayout(event)}
dataSource={this.state.dataSource}
renderRow={this.renderRow}
/>
{this.renderIndicator()}
</View>
);
}
Edit: I now understand that you want the indicator to scroll along with the list. That's a simple change from above, just add an onScroll listener to the ListView: https://sketch.expo.io/HkEjDy92e
handleScroll(event) {
const { y } = event.nativeEvent.contentOffset;
// Keep the indicator at the same position in the list using this offset.
this.setState({ scrollOffset: y });
},
With this change, the indicator actually seems to lag behind a bit because of the delay in the onScroll callback.
If you want better performance, you might consider rendering the indicator as part of your renderRow method instead. For example, if you know the indicator should appear at 10:30 am, then you would render it right in the middle of your 10am row.