Same screen with different Nested Json array data in React-native - react-native

I am trying to display same screen with different parameter in react-native. i checked with https://snack.expo.io/#react-navigation/navigate-with-params-v3. its working fine. But i have to display the different data in same screen. My expectation is in tree view structure data have to display like in our normal system tile view folder structure.
Expected Output view:
The view like normal our system folder title structure. C:/user/ReactNative/file .. like tile view.
Ex:
1.FamilyScreen.js
params : Gradpa -> while click Grandpa it will navigate to same page but the data change as 'Father'
FamilyScreen.js
params:Me - While click 'Father' it will navigate to same page but the data as 'Erick and Rose'.
The data will come from service so it may contain some more than children. it will variant. How to pass the particular data in react-native.
const family = [
{
id: 'Grandparent',
name: 'Grandpa',
age: 78,
children: [
{
id: 'Father',
name: 'Father',
age: 30,
children: [
{
id: 'Erick',
name: 'Erick',
age: 10,
},
{
id: 'Rose',
name: 'Rose',
age: 12,
},
],
},
],
},
]
Thanks

Finaly its working, here my code is
constructor(props) {
super(props)
this.state = {
res:family,
}
this.getNestedData = this.getNestedData.bind(this);
}
getNestedData (item) {
var data;
Object.keys(item).map((propKey) => {
if ( propKey === 'children'){
data=item[propKey]
}
})
this.props.navigation.push('GridScreen',{
data:data
});
}
Item = ({ item }) => {
return (
<View style={styles.item}>
<Text style={styles.title} onPress={this.getNestedData.bind(this,item)}>{item.name}</Text>
</View>
);
}
render() {
const { navigation } = this.props;
const data = navigation.getParam('data', this.state.res);
return (
<View>
<FlatList
data={data }
renderItem={({ item }) => <this.Item item={item} />}
keyExtractor={item => item.id}
numColumns={3}
/>
</View>
)
}
}

Related

React Native Handle Nested Object with Map and Display

how to handle nested object with map for display on flatlist or text or other component at react native. i tried to display using text and flatlist but didnt work, i want to display like this
this is my code,
const Schedule = () => {
const [resp, setData] = useState([]);
useEffect(() => {
const fetchData = async () => {
const respData1 = await axios(
`http://sh3ll.my.id/api/data3.json`
);
setData({ data: respData1.data.data });
};
fetchData();
},[]);
console.log('render');
if (resp.data) {
console.log("d==>", resp);
}
return (
<View style={{paddingTop:20}}>
{ resp.data && resp.data.map((items,i)=>
<Text key={i}>{`${items.date} ${items.time}`}
{items.list.map((sub)=>{ `${sub.description}`
})}
</Text>
) }
{/* <FlatList data={resp}
keyExtractor={(x,i)=>i}
renderItem={({item})=>
....?? }
/> */}
</View>
)
}
export default Schedule
Looking at your code, I assume your data object looks like this:
const resp = {
data: [
{
date: "date 1",
time: "time 1",
list: [{ description: "desc 1" }, { description: "desc 2" }]
},
{
date: "date 2",
time: "time 2",
list: [{ description: "desc 1" }, { description: "desc 2" }]
}
]
};
If that's correct, you can flatten your object by calling your own "createDescription" function that will take care of rendering the descriptions:
function createDescription(listItem) {
return <p>{listItem.description}</p>;
}
return (
<table style={{ paddingTop: 20 }}>
{resp.data &&
resp.data.map((items, i) => (
<tr key={i}>
<td>{items.date}</td>
<td>{items.time}</td>
<td>{items.list.map((sub) => createDescription(sub))}</td>
</tr>
))}
</table>
);
Now that you have your HTML correctly rendered, you can fix the layout using CSS.

Separate sectionlist data in react native

How can I separate the data to make my section list look like how it is in the picture?
https://i.stack.imgur.com/oABMf.png
It depends on the data structure you have. Lets assume you have this kind of data structure:
const data = [
{
id: 1,
text: "Fooo text 1",
description: "Foooo description 1"
},
{
id: 2,
text: "Fooo text 2",
description: "Foooo description 2"
},
]
function ListScreen() {
const sections = []
sections.push({ title: 'Title', data: data });
return (
<SectionList
sections={sections}
renderItem={({ item, index }) => <Text>{item.id}</Text>}
renderSectionHeader={SectionHeader}
keyExtractor={(item, index) => item.id.toString()}
/>
);
}
function SectionHeader({ section: { title } }) {
return (
<View style={styles.sectionHeader}>
<Text>{title}</Text>
</View>
);
}
const styles = StyleSheet.create({
sectionHeader: {
padding: 12,
},
});

React native FlatList not showing images

I want to show list of images on my app horizontally. I know if I give prop to my flat list horizontal ={true} it will be horizontal but the problem is that FlatList not showing images at all. This is what I have tried so far
const data = [
{
imageUrl: "https://c7.uihere.com/files/45/824/935/united-states-win-the-white-house-hotel-business-company-refresh-icon-thumb.jpg",
id:"1"
},
{
imageUrl: "http://via.placeholder.com/160x160",
id:"2"
},
{
imageUrl: "http://via.placeholder.com/160x160",
id:"3"
},
{
imageUrl: "http://via.placeholder.com/160x160",
id:"4"
},
{
imageUrl: "http://via.placeholder.com/160x160",
id:"5"
},
{
imageUrl: "http://via.placeholder.com/160x160",
id:"6"
}
];
export default class CircularImage extends Component {
constructor(props) {
super (props)
this.state = {
data:data
}
}
render() {
return (
<FlatList
data = {this.state.data}
renderItem = {({item}) => {
<Image styel = {styles.circularImage} source = {{uri : item.imageUrl}}/>
}}
keyExtractor ={item => {item.id.toString()}}
/>
)
}
}
You are missing a return statement in your renderItem function
<FlatList
data = {this.state.data}
renderItem = {({item}) => {
return <Image styel = {styles.circularImage} source = {{uri : item.imageUrl}}/>
}}
keyExtractor ={item => {item.id.toString()}}
/>
OR
<FlatList
data = {this.state.data}
renderItem = {({item}) => <Image styel = {styles.circularImage} source = {{uri : item.imageUrl}}/>
}
keyExtractor ={item => {item.id.toString()}}
/>
In React Native, image has to have width and height in order to show. You might missed out of that part.

How to render an array within a JSON object in react-native

I am developing an app with react-native , using RESTfull api with laravel backend , I have an object that has arrays in it . I am using it to create user's profile page . but I don't know how to render those arrays.
here is my api response:
{
meta: {
code: 200,
message: 'Success',
errors: []
},
data: {
users: [
{
personal_information: {
full_name: 'hesam sameni',
avatar: 'https://aaa/file/image/hesamsameni.jpeg',
rate: '0.0',
phone: [],
location: {
name: 'something',
lat: 00,
long: 00,
address: 'something',
distance: 00
},
about: {
quote: 'something',
bio: 'something'
},
topics: {
a: 'a',
b: 'b',
c: 'c',
d: 'd'
},
stats: {
a: 10,
b: 0,
c: 0,
d: 0,
e: 0
},
experiences: [
{
title: 'something',
organization: 'something',
start: 'something',
end: 'something'
}
],
educations: [
{
title: 'something1',
university: 'something1',
major: 'something1',
start: 'something1',
end: 'something1'
},
{
title: 'something2',
university: 'something2',
major: 'something2',
start: 'something2',
end: 'something2'
}
]
}
}
]
}
};
For example how can I show educations in user's profile?
here is the render method ( I already got data from api and stored in state {this.state.dataSource}
render method:
render() {
return (
<View>
<FlatList
data={this.state.dataSource}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => (
<View>
<Text>Name: {item.personal_information.full_name}</Text>
<Text>Rate: {item.personal_information.Rate}</Text>
<Text>Educations:</Text>
// Here I need to display all of user's educations
</View>
)}
/>
</View>
);
}
I am not sure if I had to use flatlist since it is only data for 1 specific user , but I didn't know how to render data in other way than flatlist .
try this it will help you achive what you want.
if not tell me..
<FlatList
data={this.state.itemArray}
keyExtractor={(item, index) => index.toString()}
renderItem={({item}) =>{
console.warn(item.data.users[0].personal_information.educations)
return(<FlatList
data={item.data.users[0].personal_information.educations}
keyExtractor={(item, index) => "D"+index.toString()}
renderItem={({item}) =>{
console.warn(item)
}
}/>)
}
}/>
if u want to get something from personal_information
try this example : console.warn(item.data.users[0].personal_information.full_name)
So .map itself only offers one value you care about... That said, there are a few ways of tackling this:
// instantiation
this.state.dataSource
//Using `.map` directlly
this.state.dataSource.map((obj, index)=> {
console.log(obj);
return(
<View />
)
});
// what's built into Map for you
this.state.dataSource.forEach( (val, key) => console.log(key, val) );
// what Array can do for you
Array.from( this.state.dataSource ).map(([key, value]) => ({ key, value }));
// less awesome iteration
let entries = this.state.dataSource.entries( );
for (let entry of entries) {
console.log(entry);
}
Note, I'm using a lot of new stuff in that second example... ...Array.from takes any iterable (any time you'd use [].slice.call( ), plus Sets and Maps) and turns it into an array... ...Maps, when coerced into an array, turn into an array of arrays, where el[0] === key && el[1] === value; (basically, in the same format that I prefilled my example Map with, above).
I'm using destructuring of the array in the argument position of the lambda, to assign those array spots to values, before returning an object for each el.
If you're using Babel, in production, you're going to need to use Babel's browser polyfill (which includes "core-js" and Facebook's "regenerator").
I'm quite certain it contains Array.from.
render(){
console.log(this.state.data.users[0].personal_information.educations,'cdscdscdcds')
return(
<div>
{this.state.data.users.map((value)=>{
console.log(value,'cd')
})}
</div>

How to make dynamic checkbox in react native

I am making a react native application in which i need to make checkbox during runtime.I means that from server i will get the json object which will have id and label for checkbox.Now i want to know that after fetching data from server how can i make checkbox also how can i handle the checkbox , i mean that how many number of checkbox will be there it will not be static so how can i declare state variables which can handle the checkbox.Also how can i handle the onPress event of checkbox.Please provide me some help of code .Thanks in advance
The concept will be using an array in the state and setting the state array with the data you got from the service response, Checkbox is not available in both platforms so you will have to use react-native-elements. And you can use the map function to render the checkboxes from the array, and have an onPress to change the state accordingly. The code will be as below. You will have to think about maintaining the checked value in the state as well.
import React, { Component } from 'react';
import { View } from 'react-native';
import { CheckBox } from 'react-native-elements';
export default class Sample extends Component {
constructor(props) {
super(props);
this.state = {
data: [
{ id: 1, key: 'test1', checked: false },
{ id: 2, key: 'test1', checked: true }
]
};
}
onCheckChanged(id) {
const data = this.state.data;
const index = data.findIndex(x => x.id === id);
data[index].checked = !data[index].checked;
this.setState(data);
}
render() {
return (<View>
{
this.state.data.map((item,key) => <CheckBox title={item.key} key={key} checked={item.checked} onPress={()=>this.onCheckChanged(item.id)}/>)
}
</View>)
}
}
Here's an example how you can do this. You can play with the code, to understand more how it's working.
export default class App extends React.Component {
state = {
checkboxes: [],
};
async componentDidMount() {
// mocking a datafetch
setTimeout(() => {
// mock data
const data = [{ id: 1, label: 'first' }, { id: 2, label: 'second' }];
this.setState({
checkboxes: data.map(x => {
x['value'] = false;
return x;
}),
});
}, 1000);
}
render() {
return (
<View style={styles.container}>
<Text style={styles.paragraph}>
{JSON.stringify(this.state)}
</Text>
{this.state.checkboxes.length > 0 &&
this.state.checkboxes.map(checkbox => (
<View>
<Text>{checkbox.label}</Text>
<CheckBox
onValueChange={value =>
this.setState(state => {
const index = state.checkboxes.findIndex(
x => x.id === checkbox.id
);
return {
checkboxes: [
...state.checkboxes.slice(0, index),
{ id: checkbox.id, label: checkbox.label, value },
...state.checkboxes.slice(index+1),
],
};
})
}
value={checkbox.value}
key={checkbox.id}
/>
</View>
))}
</View>
);
}
}