How to rerender FlatList inside of SmoothPicker to change data with react hooks - react-native

I'm trying to create an SmoothPicker like that:
I'm using react-native-smooth-picker and all works fine, except when I'm Changing to Feet.
When I change to Feet, I want that the list will rerender and change the data to Feet parameters, but it only happened after a scroll. Is there a way to do that?
here is my code:
const HeightPicker = () => {
const [isFeet, setIsFeet] = useState(false)
const listRef = useRef(null)
let metersHeights = []
const feetHeights = new Set()
for (i = 140; i <= 220; i++) {
metersHeights.push(i)
feetHeights.add(centimeterToFeet(i))
}
const [selected, setSelected] = useState(40)
return <View
style={{
backgroundColor: 'rgb(92,76, 73)',
paddingBottom: 20
}} >
<Toggle
style={{
alignSelf: 'flex-end',
marginVertical: 20,
marginEnd: 20
}}
textFirst="Feet"
textSecond="Meters"
onChange={(change) => {
setIsFeet(change)
}} />
<SmoothPicker
ref={listRef}
onScrollToIndexFailed={() => { }}
initialScrollToIndex={selected}
keyExtractor={(value) => value.toString()}
horizontal
showsHorizontalScrollIndicator={false}
magnet={true}
bounces={true}
extraData={isFeet}
data={isFeet ? [...feetHeights] : metersHeights}
onSelected={({ item, index }) => setSelected(index)}
renderItem={({ item, index }) => (
<Bubble selected={index === selected}>
{item}
</Bubble>
)}
/>
</View>
}

You should separate the feet & meters (the function tha generates them).
Set data with useState & make meters as default
make use of useEffect to change the data everytime you toggle.
...
useEffect(() => {
handleData(isFeet)
},[isFeet]);
const handletData = (isFeet) => {
if(isFeet){
setData(feet)
}else{
setData(meters)
}
}
....
data={data}
...

Related

React native how to render items without using any loder?

I have implemented a delete feature for the image editor app.
Case: If the user added a number of images in edit mode and wants to delete the unnecessary layer of the image from the editor then allows to delete the selected layer from the array.
Issue: when deleted the selected layer from the array the remaining image swaps its position and size to deleted image position and size. Even if I double-check the scale value and position remain the same as I fixed. This issue occurs if am not using the loder and if am using the loder then the image did not swap their position and scale.
Where I handled the states: I am handling the states in the component and I also checked if I handled the states in redux same error occurred. App speed to slow if handled with redux.
Here is my code.
const onDeleteLayerSequence = data => {
let indexing = data.length;
data.forEach(item => {
indexing--;
item.key = indexing;
});
setInputData(data);
setIsDelete(!isDelete);
};
const deleteLayer = index => {
const filterItem = [
...inputData.slice(0, index),
...inputData.slice(index + 1, inputData.length),
];
onDeleteLayerSequence(filterItem);
};
useEffect(() => {
setImageArray(inputData.filter(item => item.type == 'image'));
// setLoader(true);
}, [isDelete]);
return (
<>
<AutoDragSortableView
dataSource={inputData}
parentWidth={util.WP(100)}
childrenWidth={util.WP(100)}
childrenHeight={util.WP(12)}
keyExtractor={(item, index) => item.id}
renderItem={(item, index) => render_item(item, index)}
onDataChange={data => onSelectLayer(data)}
onClickItem={(data, i) => replaceImage(data, i)}
/>
</View>
</DraggablePanel>
<View style={styles.editImageWrapper}>
<ViewShot
ref={reference}
options={{format: 'jpg', quality: 1.0, result: 'base64'}}>
<ImageBackground
style={[
styles.templateContainer,
{backgroundColor: background},
]}
resizeMode="stretch"
source={selectTemplate}>
{isFocused &&
imageArray &&
imageArray.map((item, i) => {
return (
<component.PinchZoomView
minScale={0.1}
maxScale={5}
scale={item.scale}
translateX={item.translateX}
translateY={item.translateY}
data={value =>
modifyValues(value, item.layer, item.key)
}
key={i}
style={[
styles.pinchImagePosition,
{
zIndex: item.key,
},
]}>
<ImageCarousel>
<Image
source={{
uri: item.editImage,
height: util.WP(100),
width: util.WP(100),
}}
key={item}
resizeMode="contain"
/>
</ImageCarousel>
</component.PinchZoomView>
);
})}
</ImageBackground>
</ViewShot>
</View>
</>
)

React native Flatlist not re-rendering on state change

I realize there are a lot of questions and answers about this out there but I am fairly new to react native and most of the answers are dealing with React Components and not hooks. In the following example availableInterests is pulled from a firestore database call. Then we loop through the availableInterests so the user can select the their interests from the Flatlist of interests. Everything works great except the FLatlist does not re-render so the button that is used to select currentInterests never shows the change that an interest has been selected. Does anyone see what I am missing here?
const [availableInterests, setAvailableInterests] = useState([]);
const [currentInterests, setCurrentInterests] = useState([]);
const selectThisInterest = (item) => {
let myInterests = currentInterests;
if(myInterests.includes(item.id)) {
myInterests.pop(item.id);
} else {
myInterests.push(item.id);
}
setCurrentInterests(myInterests);
}
return <View>
<Text style={styles.text}>Select Your Interests:</Text>
<FlatList
data={availableInterests}
keyExtractor={(item, index) => index.toString()}
extraData={currentInterests}
renderItem={({ item, index }) =>
<View key={item.id}>
<Text>{item.title}</Text>
<Text>{item.description}</Text>
<Image
source={{ uri: item.icon }}
style={{ width: 100, height: 100}}
/>
<TouchableOpacity onPress={() => selectThisInterest(item)}>
<Text style={styles.buttonText}>{`${currentInterests.includes(item.id) ? 'UnSelect' : 'Select'}`}</Text>
<Text>{item.id}</Text>
</TouchableOpacity>
</View>
}>
</FlatList>
</View>
put this state below
const [currentInterests, setCurrentInterests] = useState([]);
const [extra, setExtra] = useState(0);
at the end of your function just put this
const selectThisInterest = (item) => {
....
setExtra(extra + 1)
}
I think the mistake is in your selectThisInterest function. When you are updating the currentInterests based on previous value, React doesn't recognises such a change because you are simply assigning myInterests with your currentInterests.
What you want to do is to copy that array and assign it to myInteresets and then update your values to the new copied array. Once the calculation are completed on the new myInteresets array, the setCurrentInterests() will re-render the app because now React recognises there is a change in the state.
To copy the array, you can use,
let myInterests = [...currentInterests];
change your selectThisInterest function to reflect this change,
const selectThisInterest = (item) => {
let myInterests = [...currentInterests];
if(myInterests.includes(item.id)) {
myInterests.pop(item.id);
} else {
myInterests.push(item.id);
}
setCurrentInterests(myInterests);
}

Add data to begining of FlatList without changing position

I'm trying to implement an "onBeginReached" like props in flatlist. I would like to append some data at the begining of my data array in a transparent way to user.
So using this flatList :
const App = () => {
const flatListRef = useRef(null);
const [data, setData] = useState(generateData(20));
const renderItem = ({ item }) => {
console.log(item);
return (
<View style={styles.itemContainer}>
<Text style={styles.itemText}>{item}</Text>
</View>
);
};
const handleMomentumScroll = (event) => {
console.log("Momentum end")
const xOffset = event.nativeEvent.contentOffset.x;
const index = Math.round(xOffset / 30);
if (index < 1) {
setData([-10 ,-9, -8, -7, -6,-5, -3, -2, -1, ...data]);
}
};
return (
<FlatList
style={{ width: 200, alignSelf: 'center', marginTop: 150 }}
initialScrollIndex={10}
horizontal
data={data}
snapToAlignment={'start'}
decelerationRate={'fast'}
snapToInterval={30}
getItemLayout={(data, index) => ({
length: 30,
offset: 30 * index,
index,
})}
keyExtractor={(item, index) => index.toString()}
renderItem={renderItem}
onMomentumScrollEnd={handleMomentumScroll}
/>
);
};
const styles = StyleSheet.create({
itemContainer: {
alignItems: 'center',
justifyContent: 'center',
width: 30,
height: 30,
borderRadius: 15,
backgroundColor: 'blue',
},
itemText: {
color: 'white',
},
});
(https://snack.expo.io/GUblotbZc)
If I scroll to the index 0, it'll unshift my new data to my data array. But, it'll scroll automatically to the first index of the new data array. I would like to keep the current position when unshifting new data to the array.
There is a way to impletement that behaviour ?
here is demo: https://snack.expo.io/#nomi9995/flatlisttest
use maintainVisibleContentPosition props for preventing auto scroll in IOS but unfortunately, it's not working on android but good news is pull request has come for android and need to merge with react native.
<FlatList
ref={(ref) => { this.chatFlatList = ref; }}
style={styles.flatList}
data={this.state.items}
renderItem={this._renderItem}
maintainVisibleContentPosition={{
minIndexForVisible: 0,
}}
/>
The way I did it is by inverting FlatList using the inverted prop, and also reversing my list. In this way, the top of FlatList will be at the bottom with last item in my array is visible there.
When user scrolls to the top onEndReached is triggered, and I add new items to the beginning of my array and they will be added to the top of FlatList with out changing the current visible item at the top.
You can use to Flatlist prop named "ListHeaderComponent" to add any component at the beginning of your Flatlist. https://reactnative.dev/docs/flatlist#listheadercomponent

How to add load more records with Spinner in FlatList react-native (means -10 - 10 records) manually! not from using server side

Hi I am developing sample application based on FlatList this is my code here. Actually i showed entire records like i have 50 records to my account . But now i am displaying entire 50 records. Bur i need show 10 after adding to 10 records. But i don't know adding to FlatList.
Here this is my code:
<FlatList
data={this.state.profiles}
renderItem={({ item, index }) => this.renderCard(item, index)}
keyExtractor={item => item.id}
ItemSeparatorComponent={() => <Divider style={{ marginTop: 5, marginLeft: width * 0.2 + 20 }} parentStyle={{ backgroundColor: globalStyles.BG_COLOR, alignItems: 'baseline' }} />}
/>
renderCard (profile, index) {
console.log('rendercard', profile);
//
return (
<View key={profile.id}>
<ProfileCard
profile={profile}
style={styles.card}
onPress={() => this.props.screenProps.rootNavigation.navigate('Profile', { profile: this.state.profile, id: profile.id })}
// onPress={() => alert('PROFILE')}
onAddClick={() => this.setState({ connectionPageVisible: true, cardProfile: profile })}
connectedIds={(this.props.screenProps && this.props.screenProps.connectedIds) || this.props.connectedIds}
/>
</View>
);
}
Please show me load more records with Activity Indicator.
Thanks in Advance
If I have understood your problem properly, then you are looking for infinite scrolling in Flatlist. You can achieve this with the help of onEndReached and onEndThreshold attributes.
Consider the following prototype
Assuming you are storing records into this.state.profiles.
Pulling new records from the server
Setting initial page number in the constructor
constructor(props){
super(props);
this.state = { page: 0}
}
Fetching new records
fetchRecords = (page) => {
// following API will changed based on your requirement
fetch(`${API}/${page}/...`)
.then(res => res.json())
.then(response => {
this.setState({
profiles: [...this.state.profiles, ...response.data] // assuming response.data is an array and holds new records
});
});
}
to handle scroll
onScrollHandler = () => {
this.setState({
page: this.state.page + 1
}, () => {
this.fetchRecords(this.state.page);
});
}
Render function
render() {
return(
...
<FlatList
data={this.state.profiles}
renderItem={({ item, index }) => this.renderCard(item, index)}
keyExtractor={item => item.id}
ItemSeparatorComponent={() => <Divider style={{ marginTop: 5, marginLeft: width * 0.2 + 20 }} parentStyle={{ backgroundColor: globalStyles.BG_COLOR, alignItems: 'baseline' }} />}
onEndReached={this.onScrollHandler}
onEndThreshold={0}
/>
...
);
}
Local updates
If you have already pulled all the data, but want to show only 10 at a time, then all you need to do is change the fetchRecords
fetchRecords = (page) => {
// assuming this.state.records hold all the records
const newRecords = []
for(var i = page * 10, il = i + 10; i < il && i < this.state.records.length; i++){
newRecords.push(this.state.records[i]);
}
this.setState({
profiles: [...this.state.profiles, ...newRecords]
});
}
Above approach will show Activity Indicator while pulling records.
Hope this will help!

React Native - SectionList numColumns support

FlatList has numColumns support. How to set numColumns with SectionList?
Github issue: SectionList renderItem multi item support #13192
Here is my solution to numColumns for SectionList. If you have better let me know please.
class Example extends Component {
static propTypes = {
numColumns: PropTypes.number
};
static defaultProps = {
numColumns: 2
};
_renderSection = data => <Section {...data} />;
_renderItem = ({ section, index }) => {
const { numColumns } = this.props;
if (index % numColumns !== 0) return null;
const items = [];
for (let i = index; i < index + numColumns; i++) {
if (i >= section.data.length) {
break;
}
items.push(<Item item={section.data[i]} />);
}
return (
<View
style={{
flexDirection: "row",
justifyContent: "space-between"
}}
>
{items}
</View>
);
};
render() {
return (
<SectionList
sections={dumyData}
style={styles.container}
renderItem={this._renderItem}
renderSectionHeader={this._renderSection}
/>
);
}
}
It is possible to use FlatList with numColumns prop as the renderItem of SectionList.
const data = [ //Notice [[...]] instead of [...] as in the RN docs
{data: [[...]], title: ...},
{data: [[...]], title: ...},
{data: [[...]], title: ...},
]
render () {
return (
<SectionList
renderItem={this._renderSectionListItem}
renderSectionHeader={this._renderSectionHeader}
sections={data}
/>
)
}
renderSectionListItem = ({item}) => {
return (
<FlatList
data={item}
numColumns={3}
renderItem={this.renderItem}
/>
)
}
Digging this issue up, I came with a solution similar to Pir Shukarullah Shah 's.
I'm using FlatList instead of my regular item, taking into account only the first item in <SectionList/>'s renderItem method.
_renderList = ({ section, index }) => {
if (index !== 0) return null;
return (
<FlatList numColumns={columns}
columnWrapperStyle={styles.container}
data={section.data}
renderItem={this._renderItem}
keyExtractor={keyExtractor}
/>
)
}
...
<SectionList
renderItem={this._renderList}
renderSectionHeader={this._renderSectionHeader}
sections={itemList}
keyExtractor={keyExtractor}
/>
I found there is a simple solution. Please try adding the following property to the
contentContainerStyle={{
flexDirection : 'row',
justifyContent : 'flex-start',
alignItems : 'flex-start',
flexWrap : 'wrap'
}}
Besides, set and render the Section Header with the Width equal to the SectionList width. Otherwise, the list items will be displayed following the Section Header in row direction.
const DATA = [
{
renderItem: ({ item, index }) => {
return (<View style={{flexDirection:'row', alignItems:'center', justifyContent:'space-between', }}>
{item.map((elem,index)=>(<View style={{ borderColor: 'black', borderWidth: 2, minWidth:100 }}>
<Text>{elem.value}</Text>
</View>))
}
</View>);
},
data: [
[{id:'1', value:'Pizza'}, {id:'2', value:'Burger'}, {id:'3', value:'Onion Rings'}], //this array length will be noOfColumns
[{id:'4', value:'Risotto'}, {id:'5', value:'French Fries'}, {id:'6', value:'Water'}],
],
},
<SectionList
ref={listRef}
sections={DATA}
keyExtractor={_keyExtractor}
/>
I had the same logic like Pir Shukarullah Shah. The idea of using flexWrap is not recommended by react and warns to use numColumns prop in flatlist. If anyone has a better solution please add.
let items = []
const renderItem = ({ item, index }) => {
if (index % 2 === 0) {
items = []
items.push(<Card cloth={item} index={index} />)
return (index === clothes[0].data.length - 1) ? <View style={styles.row}>{items}</View> : null
}
items.push(<Card cloth={item} index={index} />)
return (
<View style={styles.row}>
{items}
</View>
)
}
The section list is :
<SectionList
sections={clothes}
renderItem={renderItem}
keyExtractor={(item, index) => index}
renderSectionHeader={renderSectionHeader}
stickyHeaderHiddenOnScroll={true}
stickySectionHeadersEnabled={true}
onEndReached={endReachedHandler}
onEndReachedThreshold={0.25}
contentContainerStyle={{ paddingBottom: '25%' }}
/>
The structure for clothes is:
let one = {name: 'Jeans pant'}
let many = Array(10).fill(one) // creating more dummy clothes
let cl = [{data: many, title: 'Cloth'}]
let [clothes, setClothes] = useState(cl)
I needed only one section so in cl array I wrote only one object initially if you want to have multiple sections you would need to add to the clothes array.
This is a slightly updated version of Pir Shukarullah Shah accepted answer to show a more functional approach over class approach.
// render a single section.data item
const itemRenderer = (item) => <Text>{item}</Text>
return (
<SectionList
sections={listData}
renderItem={(section, index) => {
if (index % numCols) { // items are already consumed
return null
}
// grab all items for the row
const rowItems = section.data.slice(index, index+numCols)
// wrap selected items in a "row" View
return <View
style={{
flexDirection:"row",
justifiyContent:"space-between"
}}
>{rowItems.map(itemRenderer)}</View>
}}
/>)
Also if you have fixed width items you can calculate numCols dynamically here's an example for a full screen width SectionList:
const itemFixedWidth = 24
const listWidth = useWindowDimensions().width
const numCols = Math.floor(listWidth / itemFixedWidth)
I'm a new user to this site, otherwise I'd just upvote Fong's answer above. Slick, that one.
Just to further clarify the last sentence he wrote.
I used Dimensions.get('window').width on the section header like so:
renderSectionHeader={({ section: { title } }) => (
<View
style={{
width: Dimensions.get('window').width,
}}
>
<Text>
{title}
</Text>
</View>
)}
Though that method does throw a console warning about using flexWrap...