Reputation: 63
I was working with code supplied from my university to practise with but it now throws up the error message 'invariant violation: text strings must be rendered within a text component' I have even completely made a new file to run it fresh with the original code but still get that error.
is there a reason as to why this has suddenly happened and how can i fix it please?
Thank you
import React from 'react';
import { StyleSheet, FlatList, ActivityIndicator, Text, View } from 'react-native';
export default class FetchExample extends React.Component {
constructor(props) {
super(props);
this.state = { isLoading: true }
}
componentWillMount () {
const localMovieData = require('./assets/test.json');
this.setState({
isLoading: false,
dataSource: localMovieData.movies,
}, function () {
});
}
_renderItem = (info) => {
return <Text>{this.state.dataSource.map((movie, index) => (
<p>Hello, {movie.title} from {movie.releaseYear}!</p>
))}</Text>
}
render() {
return (
<View style={{ flex: 1, paddingTop: 20 }}>
<FlatList
data={this.state.dataSource}
renderItem={this._renderItem}
keyExtractor={({ id }, index) => id}
/>
</View>
);
}
}
JSON Data
{
"title": "The Basics - Networking",
"description": "Your app fetched this from a remote endpoint!",
"movies": [
{ "id": "1", "title": "Star Wars", "releaseYear": "1977" },
{ "id": "2", "title": "Back to the Future", "releaseYear": "1985" },
{ "id": "3", "title": "The Matrix", "releaseYear": "1999" },
{ "id": "4", "title": "Inception", "releaseYear": "2010" },
{ "id": "5", "title": "Interstellar", "releaseYear": "2014" }
]
}
Upvotes: 0
Views: 239
Reputation: 7127
Main culprit is the < p > primitive in the code. Since this is react-native, should use < Text > instead of < p > .
_renderItem = (info) => {
return <View>{this.state.dataSource.map((movie, index) => (
<Text>Hello, {movie.title} from {movie.releaseYear}!</Text>
))}</View>
}
Upvotes: 2
Reputation: 9769
Try this...
It's recommended to use componentDidMount
for api call because componentWillMount
is deprecated. reference
Code- you can import like this
import data from './test.json';
export default class App extends React.Component {
state={
dataSource:data
}
_renderItem = (info) => {
return <Text>{this.state.dataSource.map((movie, index) => (
<Text>Hello, {movie.title} from {movie.releaseYear}</Text>
))}</Text>
}
render() {
return (
<View style={{ flex: 1, paddingTop: 20 }}>
<FlatList
data={this.state.dataSource}
renderItem={this._renderItem}
keyExtractor={({ id }, index) => id}
/>
</View>
);
}
}
Upvotes: 0