Reputation: 1854
I am trying to create a SectionList
from a json file named notes.json
. Basically one object in the notes
json array will correspond to one SectionList
entry. I already load the json array in notesData
. However, when i try to use notesData
as a source for my SectionList
i get the error: TypeError: undefined is not an object (evaluating 'props.sections.reduce')
Here is my code:
import React from 'react';
import { Text, View, SectionList, ListItem, H1 } from 'react-native';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { styles } from '~/containers/Notes/styles';
import { notes } from './Notes.json';
const notesData = [];
Object.keys(notes).forEach((key) => {
notesData.push(notes[key]);
});
class NotesContainer extends React.Component {
render() {
return (
<View style={styles.container}>
<SectionList
renderItem={({ item }) => <ListItem title={item.RELEASE_NOTE} />}
renderSectionHeader={({ section }) => <Text title={section.RELEASE_VERSION} />}
sections={this.notesData}
/>
</View>
);
}
}
export { NotesContainer };
export default connect(null, null)(NotesContainer);
Here is my Notes.json
{
"notes": [
{
"RELEASE_VERSION": "0.1.1",
"RELEASE_DATE": "01 Mar 2018",
"RELEASE_NOTE": [
"General bug fixes"
]
},
{
"RELEASE_VERSION": "0.1.0",
"RELEASE_DATE": "01 Feb 2018",
"RELEASE_NOTE": [
"Initial Launch"
]
}
]
}
Upvotes: 2
Views: 2692
Reputation: 24660
Your data structure for SectionList
is not correct, it should have a data
prop with the array of data you want to render in that section. Below there is an example for the data you have.
section
An object that identifies the data to be rendered for a given section.
Properties:
data
arrayThe data for rendering items in this section. Array of objects, much like FlatList's data prop.
Example
export default class App extends Component {
constructor() {
super();
this.notesData = Object.keys(notes).map((key) => {
return { data: notes[key].RELEASE_NOTE, version: notes[key].RELEASE_VERSION }
});
}
render() {
return (
<View style={styles.container}>
<SectionList
renderItem={({ item }) => <Text>{item}</Text>}
renderSectionHeader={({ section }) => <Text>{section.version}</Text>}
sections={this.notesData}
/>
</View>
);
}
}
Upvotes: 3
Reputation: 526
You can do lists which based on your json data with ListView component;
constructor(props) {
super(props);
this.ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 });
this.listNotes = this.listNotes.bind(this);
this.state = {
notesData: this.ds.cloneWithRows({}),
};
}
componentWillMount() {
this.setState({ notesData: this.ds.cloneWithRows([notes]) });
}
renderState() {
return (
<View>
<ListView
dataSource={this.state.notesData}
enableEmptySections
renderRow={this.listNotes}
/>
</View>
);
}
listNotes(rowData) {
return (
<View>
{rowData.map((item, key) => (
<View key={key}>
...
</View>
))}
</View>
);
}
render() {
<ScrollView>
{this.renderState()}
</ScrollView>
}
Upvotes: -1