This is the continuation of previous article Getting started with React Native Template Design – Tutorial Part I. Today’s article and video tutorial explains how to parse and render the json data using some of the best React Native packages. It explains how to make ajax calls using fetch. Fetch is the networking API, which is chosen by React Native to get the JSON data and render it in the page. I hope embedded videos with blog posts are more advantageous for you to learn. I appreciate to take any feedback if you have, so that I can make it better.
Video Tutorial - React Native Parsing JSON Data
Create a New Component
appBody.js
Here super and componentDidMount are React builtin functions. Using super you can initialize state this value and componentDidMount is calls first.
import React, {Component} from 'react';
import {Text} from 'react-native';
import {Content, Card, CardItem, Body} from 'native-base';
import AppBodyData from './appBodyData';
export default class AppBody extends Component {
constructor(){
super()
this.state ={
data:[]
}
}
getData(){
return fetch('https://www.thewallscript.com/blogfeed/javascript/10')
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson.feed.entry});
})
.catch((error) => {
console.error(error);
});
}
componentDidMount() {
this.getData();
}
render() {
return (
<AppBodyData data = {this.state.data}/>
);
}
}
module.export = AppBody;
import {Text} from 'react-native';
import {Content, Card, CardItem, Body} from 'native-base';
import AppBodyData from './appBodyData';
export default class AppBody extends Component {
constructor(){
super()
this.state ={
data:[]
}
}
getData(){
return fetch('https://www.thewallscript.com/blogfeed/javascript/10')
.then((response) => response.json())
.then((responseJson) => {
this.setState({data: responseJson.feed.entry});
})
.catch((error) => {
console.error(error);
});
}
componentDidMount() {
this.getData();
}
render() {
return (
<AppBodyData data = {this.state.data}/>
);
}
}
module.export = AppBody;
appBodyData.js
This component renders all of the JSON data titles.
import React, {Component} from 'react';
import {Text} from 'react-native';
import { Content, Card, CardItem, Body, Left} from 'native-base';
export default class AppBodyData extends Component {
render() {
let articles = this.props.data.map(function (articleData, index) {
return (
<Card>
<CardItem>
<Body>
<Text>
{articleData.title.$t}
</Text>
</Body>
</CardItem>
</Card>
)
});
return (
<Content>
{articles}
</Content>
);
}
}
module.export = AppBodyData;
import {Text} from 'react-native';
import { Content, Card, CardItem, Body, Left} from 'native-base';
export default class AppBodyData extends Component {
render() {
let articles = this.props.data.map(function (articleData, index) {
return (
<Card>
<CardItem>
<Body>
<Text>
{articleData.title.$t}
</Text>
</Body>
</CardItem>
</Card>
)
});
return (
<Content>
{articles}
</Content>
);
}
}
module.export = AppBodyData;
Installing React Packages
This JSON feed contains HTML and improper data, we need to install packages/plugins for improving this.
Time Ago
This package helps to convert timestamp to time ago text.
$npm install react-native-timeago --save
HTMLView
Binding HTML tags data to the component.
$npm install react-native-htmlview --save
Fit Image
For different mobile dimensions, you need to make images in responsive style.
$npm install react-native-fit-image --save
Helper Function
Create a file directory under src folder.
helpers.js
This file contains two functions, GetImage is filtering first image source from HTML content. ContentSnippet is displaying first 50 words.
export function GetImage(content){
var myRegexp = new RegExp(/<img.*?src="(.*?)"/);
var match = myRegexp.exec(content);
if (match){
return match[1];
}
}
export function ContentSnippet(content){
return content.split(/\s+/).slice(0, 30).join(" ")+"...";
}
var myRegexp = new RegExp(/<img.*?src="(.*?)"/);
var match = myRegexp.exec(content);
if (match){
return match[1];
}
}
export function ContentSnippet(content){
return content.split(/\s+/).slice(0, 30).join(" ")+"...";
}
Video Tutorial - React Native Helper/Injectable Functions
appBodyData.js
Final Code with all of the implementations.
import React, {Component} from 'react';
import {Text} from 'react-native';
import HTMLView from 'react-native-htmlview';
import TimeAgo from 'react-native-timeago';
import FitImage from 'react-native-fit-image';
import {GetImage, ContentSnippet} from '../helpers/helpers';
import {Content, Card, CardItem, Body, Left, Thumbnail, Button, Icon} from 'native-base';
export default class AppBodyData extends Component {
render() {
let articles = this.props.data.map(function (articleData, index) {
return (
<Card>
<CardItem>
<Left>
<Thumbnail source={require('../img/SrinivasTamada.png')}/>
<Body>
<Text>{articleData.title.$t}</Text>
</Body>
</Left>
</CardItem>
<CardItem>
<FitImage source={{uri: GetImage(articleData.content.$t)}}/>
</CardItem>
<CardItem content>
<HTMLView value={ContentSnippet(articleData.content.$t)}/>
</CardItem>
<CardItem>
<Button transparent>
<Icon active name="time"/>
<Text>
<TimeAgo time={articleData.published.$t}/>
</Text>
</Button>
<Button transparent>
<Icon active name="chatbubbles"/>
<Text>
{articleData.thr$total.$t} Comments
</Text>
</Button>
</CardItem>
</Card>
)
});
return (
<Content>
{articles}
</Content>
);
}
}
module.export = AppBodyData;
import {Text} from 'react-native';
import HTMLView from 'react-native-htmlview';
import TimeAgo from 'react-native-timeago';
import FitImage from 'react-native-fit-image';
import {GetImage, ContentSnippet} from '../helpers/helpers';
import {Content, Card, CardItem, Body, Left, Thumbnail, Button, Icon} from 'native-base';
export default class AppBodyData extends Component {
render() {
let articles = this.props.data.map(function (articleData, index) {
return (
<Card>
<CardItem>
<Left>
<Thumbnail source={require('../img/SrinivasTamada.png')}/>
<Body>
<Text>{articleData.title.$t}</Text>
</Body>
</Left>
</CardItem>
<CardItem>
<FitImage source={{uri: GetImage(articleData.content.$t)}}/>
</CardItem>
<CardItem content>
<HTMLView value={ContentSnippet(articleData.content.$t)}/>
</CardItem>
<CardItem>
<Button transparent>
<Icon active name="time"/>
<Text>
<TimeAgo time={articleData.published.$t}/>
</Text>
</Button>
<Button transparent>
<Icon active name="chatbubbles"/>
<Text>
{articleData.thr$total.$t} Comments
</Text>
</Button>
</CardItem>
</Card>
)
});
return (
<Content>
{articles}
</Content>
);
}
}
module.export = AppBodyData;
Part 3: React Native Routing and Navigation.
nice! thanks man
ReplyDeletenice article and thanks sir
ReplyDeleteCan you please help me, how to put captured image to folder and path stored to mysql database in react native android app
ReplyDeleteUndefined is not an object ('evaluating this.props.data.map')
ReplyDeleteplease help me sir...
How to React-Native Nested Array in json. for example i want to get taxonomies
ReplyDelete{
"id": 17421,
"title": "LEGO Power Functions 88002 Train Motor",
"content": "",
"excerpt": "",
"stock": "0",
"parts_shape_id": "0",
"parts_color_id": "0",
"condition_id": "0",
"sequence": "0",
"brand_count": "0",
"media_id": "0",
"items": [
{
"id": 17421,
"product_id": "17421",
"item_title": "",
"item_description": "",
"sku": "88002",
"type": "variant",
"status": "active",
"stock_status": "1",
"schedule_sale": "0",
"stock": "34",
"stock_available": "34",
"price": "350000.0000",
"sale_price": "0.0000",
"msrp": "0.0000",
"sale_start_date": "0000-00-00 00:00:00",
"trigger_inventory": "",
"taxonomies": [
{
"id": 1186,
"cat_id": null,
"name": "Black",
"description": null,
"store_data": "",
"pivot": {
"item_id": "17421",
"taxonomy_id": "1186"
}
},
{
"id": 2,
"cat_id": null,
"name": "Brand New",
"description": "",
"taxonomy_slug": "brand-new",
"taxonomy_type": "condition",
"parent": "0",
"count": "439",
"created_at": "2015-10-12 14:49:48",
"updated_at": "2017-01-06 17:40:42",
"modified_by": "1",
"seo_title": null,
"seo_keyword": null,
"seo_description": null,
"data": "",
"store_data": "",
"pivot": {
"item_id": "17421",
"taxonomy_id": "2"
}
}
],
"medias": []
}
],
"medias": []
},
thanks a lot for this great tutorial but there is a problem , the json link return no data , is there an alternative one
ReplyDeleteplz help
{"top_menu":[{"id":1,"name":"Menu 1"},{"id":2,"name":"Menu 2"}],"left_menu":[{"id":1,"name":"Menu 1"},{"id":2,"name":"Menu 2"},{"id":3,"name":"Menu 3"}]} I have above json array, parsed and set state using this.setState({ tabScreen: responseJson.top_menu });
ReplyDeleteI unable to access array elements like {this.state.tabScreen[1].name} while rendering text.
Hi great hardwork.
ReplyDeleteThanks for sharing.
Very informative!! I was just trying with the code build and it was working. But I can see there is much space between the header and the body. The body is not starting adfter the header ther is much space in between them.
ReplyDeleteDo you know what could be the reason?