Is there a way to get past the error "TypeError: headers.map is not a function"? - react-native

TypeError: headers.map is not a function
function TableComponent(headers, values) {
if (!headers || !values) return null;
const optionsPerPage = [2, 3, 4];
const [page, setPage] = useState(0);
const [itemsPerPage, setItemsPerPage] = useState(optionsPerPage[0]);
console.log(headers);
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<DataTable>
{headers.map(({ title, numeric }) => <DataTable.Title key={title} numeric={numeric}>{title}</DataTable.Title>)}
{values.map((value, index) => <DataTable.Row key={index}>
{headers.map(({ title }) => <DataTable.Cell key={title}>{value[title]}</DataTable.Cell>)}
</DataTable.Row>)}
<DataTable.Pagination
page={page}
numberOfPages={3}
onPageChange={(page) => setPage(page)}
label="1-2 of 6"
optionsPerPage={optionsPerPage}
itemsPerPage={itemsPerPage}
setItemsPerPage={setItemsPerPage}
showFastPagination
optionsLabel={'Rows per page'}
/>
</DataTable>
</View>
);
}
Maybe I am using the wrong solution for this problem entirely. I am open to alternatives if this simply cannot work.

Per the comments, it looks like headers is an object and not an array, which explains "headers.map is not a function". Instead, use headers.headers.map(...) because headers.headers is an array.

Related

how to get list index using react-native-swiper-flatlist?

the library quotes the getCurrentIndex function, but I can't implement it in my code. Could someone show me an example of use? I couldn't find it anywhere.
You need to pass a ref via the ref prop to the component. This will give you access to the getCurrentIndex function.
Here is a minimal example.
const data = [0, 1, 2, 3, 4]
const App = () => {
const scrollRef = React.useRef(null);
return <View style={styles.container}>
<SwiperFlatList
ref={scrollRef}
data={data}
renderItem={({ item }) => (
<TouchableOpacity onPress={() => console.log(scrollRef.current.getCurrentIndex())} style={{width: 200, height: 200, backgroundColor: "red"}}>
</TouchableOpacity>
)}
/>
</View>
};
The above will print the current index onPress of the rendered item. The key part is scrollRef.current.getCurrentIndex().

How I make this input in react native customable?

I need a verification input and want to make it like in this picture:
I know how to make it but not customable. Maybe I want to make 4 or 5.
I can make it like this
const input2 = useRef();
const input3 = useRef();
const input4 = useRef();
const input5 = useRef();
<TextInput onChangeText={(e) => (setText(e), input2.focus() ) } />
<TextInput ref={(input) => { input2 = input } } />
But then its hardcoded. How can I make it customable ?
You could use react-native-confirmation-code-field which is highly customizable.
Here is a basic example using 4 inputs instead of 5. In fact, you can use any number of inputs.
const [value, setValue] = useState("")
const ref = useBlurOnFulfill({ value, cellCount: 4 })
const [props, getCellOnLayoutHandler] = useClearByFocusCell({
value,
setValue,
})
return (
<SafeAreaView style={{ margin: 40, marginTop: 80 }}>
<CodeField
ref={ref}
{...props}
// Use `caretHidden={false}` when users can't paste a text value, because context menu doesn't appear
value={value}
onChangeText={setValue}
cellCount={4}
keyboardType="number-pad"
textContentType="oneTimeCode"
renderCell={({ index, symbol, isFocused }) => (
<Text
style={{
width: 40,
height: 40,
lineHeight: 38,
fontSize: 24,
borderWidth: 2,
borderColor: "#00000030",
textAlign: "center",
}}
key={index}
onLayout={getCellOnLayoutHandler(index)}>
{symbol || (isFocused ? <Cursor /> : null)}
</Text>
)}
/>
</SafeAreaView>
In general this component is very customizable. You can render your own input components, etc.
The above code yields the following very simple output. Designing the exact same component as given in your picture boils to designing a custom cell inside the render function.

Component only reachable by scrolling regardless of window size

I'm trying to make a layout so that the later parts of the view are only reachable by scrolling.
Currently I'm using Dimensions to generate Views with the correct height. Is there a better way of doing so? My current solution doesn't seem too correct.
export default function MyApp() {
const height = Dimensions.get('window').height;
return (
<View style={styles.container}>
<ScrollView>
<View style={{backgroundColor: 'green', height:height}}/>
<View style={{backgroundColor: 'red', height:40}}/>
</ScrollView>
</View>
);
}
const styles = StyleSheet.create({
container:{
backgroundColor: 'white',
flex: 1
}
});
You can use VirtualizedList component, for example as
<VirtualizedList
data={['body']}
renderItem={({ item }) => (
<View style={styles.screen}>
{/* Put more content for body */}
</View>
)}
keyExtractor={(item, index) => index.toString()}
getItemCount={() => {
return 1;
}}
getItem={(data, index) => {
return data[index];
}}>
</VirtualizedList>
Your solution work, but not good and it have downside, when you change your phone orientation to landscape there will be bug. I dont like using Dimensions in my code unless there is no other way or use Dimensions addEventListener to listen window size and update component whenever window size change. I will suggest you a better way.
First, create a component called LayoutSizeAwareView, after this view rendered, we will catch it size from onLayout props and use them to render it children.
const LayoutSizeAwareView = (props) => {
const [size, setSize] = React.useState({width: 0, height: 0});
return (
<View
...props,
onLayout={(e) => {
setSize({
width: e.nativeEvent.layout.width,
height: e.nativeEvent.layout.height,
})
props.onLayout(e)
}}
>
{props.children(size)}
</View>
)
}
And then, in your case, use it like this
export default function MyApp() {
return (
<LayoutSizeAwareView style={styles.container}>
{({width, height}) => {
return (
<ScrollView>
<View style={{backgroundColor: 'green', height: height}}/>
<View style={{backgroundColor: 'red', height: 40}}/>
</ScrollView>
)
}}
</View>
);
}
const styles = StyleSheet.create({
container:{
backgroundColor: 'white',
flex: 1
}
});
This way your code look even cooler, there will be some typo in my code since I dont have IDE here, but you might get the idea.

How to use checkbox in loop in react naive

How to use checkbox in loop with diffrent key when i use in loop and click on any one after than check all loop checkbox give me solution
You can create an array of solutions in state:
...
state.solutions = [
{value:false},
{value:false},
{value:false}
]
Create a changes event handler:
changeEvent = (ev, index) => {
let tmp_solution = [...state.solutions];
tmp_solutions[index].value = !tmp_solutions[index].value;
this.setState({solutions: tmp_solution})
}
Create the checkboxes render function:
const checkBoxes = this.state.solutions.map((index) =>{
return(
<CheckBox
value={this.state.solutions[index].value}
onValueChange={(ev) => this.changeEvent(ev, index)} key={index}
/>
)
});
Render all the checkboxes:
render() {
<View>
{checkBoxes}
</View>
}
...
sorry if there are errors
Well, suppose that you have a data, so you can use map to do that. In order to save the answers also you can use index in setSetate as below. I use the react-native-checkbox-heaven component to have the check Box:
import CheckBox from 'react-native-checkbox-heaven';
renderContentCheckBox=()=>{
console.log("[renderContent] your data", this.state.data);
return Object.keys(this.state.data).map(function (item, index) {
return (<View key={index} style={{ alignItems: 'flex-start', justifyContent: 'flex-start', width: Dimensions.get('window').width / 1.1, }}>
<CheckBox
label={item.title}
labelStyle={styles.labelStyle}
iconSize={28}
iconName='matMix'
checked={this.state.check1}
checkedColor='#44FF00'
uncheckedColor='#FFFFFF'
onChange={(val) => {(value) => { that.setState({ ["CheckBox" + index]: value, }); console.log("radio" + index, value);
}}
/>
</View>
);
}
}
Then you can use it inside the render:
render() {
return (<View>
{this.renderContentCheckBox(this)}
</View>
);
}

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...