Read data from json object in reactjs showing error - reactjs

I have facing a problem with getting data from json object with react. Here is my example data:
const data = [
{
"name": "Adele",
"age": "17",
"exampleValue": "Dummy"
},
{
"name": "Adele",
"age": "17"
}
]
But when i'm trying to get data from the object with "exampleValue". it showing me error.
Is there any way to solve it without adding "exampleValue" in second object?

To read the elements which may present in the node can be read by adding certain condition. Like in your cases you can check if the element in the json node present or not using "hasOwnProperty"
Example
import React, { useState, useEffect, useRef } from "react";
import { Text, View, StyleSheet } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default function App() {
const [arr, setArr] = useState([{
"name": "Adele",
"age": "17",
"exampleValue": "Dummy"
},
{
"name": "Adele",
"age": "17"
},
{
"name": "Adele",
"age": "17",
"exampleValue": "User"
}]);
const renderRow=()=>{
return arr.map((item, index)=>
<div style={{fontSize:18}}>
{item.hasOwnProperty("exampleValue")? item.exampleValue:null}
</div>
)
}
return (
<View style={styles.container}>
{renderRow()}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
}
});
Working example: https://snack.expo.dev/L_a4aNEL1

Related

Invariant Violation: View config getter callback for component `Home` must be a function (received `undefined`)

I want to call the function using the key name from the array on the tab.screen component.
my code is like this:
import React from 'react';
import { Text, View, TouchableOpacity, Modal } from 'react-native';
import AsyncStorage from '#react-native-community/async-storage';
import Icon from 'react-native-vector-icons/FontAwesome5';
import { createBottomTabNavigator } from '#react-navigation/bottom-tabs';
import Home from '../mainscreen/GeneralScreen';
import Core from '../mainscreen/CoreScreen';
import Docs from '../mainscreen/GeneralScreen';
import ESS from '../mainscreen/GeneralScreen';
import General from '../mainscreen/GeneralScreen';
import HR from '../mainscreen/GeneralScreen';
import Payroll from '../mainscreen/GeneralScreen';
import Server from '../mainscreen/CoreScreen';
const Tab = createBottomTabNavigator();
const tabcomponents = {
"Home" : Home,
"Core" : Core,
"Docs" : Docs,
"ESS" : ESS,
"General" : General,
"HR" : HR,
"Payroll" : Payroll,
"Server" : Server
};
class TabNavigator extends React.Component {
constructor() {
super();
this.state = {
dashboardtab:[],
}
this.tabnavigatorasync();
}
tabnavigatorasync = async () => {
try {
const dashboardtab = await AsyncStorage.getItem('dashboardtab');
const dashboardtabParse = JSON.parse(dashboardtab);
this.setState({dashboardtab: dashboardtabParse});
//console.log('isi dari tab navigator: ', this.state.dashboardtab);
//console.log('------------------------------------------------');
//console.log('isi dari tab navigator 2: ', this.state.dashboardtab2[0].label);
} catch (error) {
}
}
render(){
//console.log('dashboardtab', this.state.dashboardtab);
const tabnavigatorRender = this.state.dashboardtab.map((item, index) =>
const tabcomponentsrender = tabcomponents[item.admintab.label];
return <Tab.Screen name={item.admintab.label} component={tabcomponentsrender} key={index}/>
);
return(
<Tab.Navigator>
{tabnavigatorRender}
</Tab.Navigator>
)
}
}
export default TabNavigator;
the result appears an error like this:
Invariant Violation: View config getter callback for component Home must be a function (received undefined)
This is the contents of the array:
[
{
"tab_id": "home",
"order": 10,
"admintab": {
"label": "Home",
}
},
{
"tab_id": "core",
"order": 1,
"admintab": {
"label": "Core",
}
},
{
"tab_id": "docs",
"order": 2,
"admintab": {
"label": "Docs",
}
},
{
"tab_id": "ess",
"order": 50,
"admintab": {
"label": "ESS",
}
},
{
"tab_id": "general",
"order": 45,
"admintab": {
"label": "General",
}
},
{
"tab_id": "hr",
"order": 40,
"admintab": {
"label": "HR",
}
},
{
"tab_id": "payroll",
"order": 42,
"admintab": {
"label": "Payroll",
}
},
{
"tab_id": "server",
"order": 70,
"admintab": {
"label": "Server",
}
}
]
is there something wrong with the code i made?
In your case, you want to use Dynamic Component Names.
First of all import your tabs.
import Home from 'path_to_your_tab_component/Home';
import Core from 'path_to_your_tab_component/Core'; // and so on
Then pass them in the object and give them a key based on their names.
const components = {
"Home": Home
"Core": Core // and so on
}
Inside the map, create a component from this object.
const tabnavigator = this.state.dashboardtab.map((item, index) => {
const TabComponent = components[item.admintab.label];
return <Tab.Screen name={item.admintab.label} component={TabComponent} key={index}/>
});

"TypeError: Cannot read property 'name' of undefined" when looping on JSON

I have a JSON like this :
{
"cards": [
{
"name": "aquaman",
"img": "aquaman.png"
},
{
"name": "batman",
"img": "batman.png"
},
{
"name": "captainamerica",
"img": "captainamerica.png"
},
{
"name": "deadpool",
"img": "deadpool.png"
},
{
"name": "flash",
"img": "flash.png"
},
{
"name": "greenlantern",
"img": "greenlantern.png"
},
{
"name": "ironman",
"img": "ironman.png"
},
{
"name": "spiderman",
"img": "spiderman.png"
},
{
"name": "ironfist",
"img": "ironfist.png"
},
{
"name": "thepunisher",
"img": "thepunisher.png"
},
{
"name": "wonderwoman",
"img": "wonderwoman.png"
},
{
"name": "xman",
"img": "xman.png"
}
]
}
and I want to loop on these objects and to render a div with a backgroundImage with the img property of every object,
I tried this, but it tells me:
TypeError: Cannot read property 'name' of undefined
import React, { useEffect, useState } from "react";
import cardsJson from "../../../utils/cards.json";
const [cards, setCards] = useState();
useEffect(() => {
setCards(cardsJson.cards);
}, [cards]);
{cards &&
cards.map((card: any, index: number) => (
<div key={card.name} className="cardHero">
<div className="front"></div>
<div
className="back"
style={{
backgroundImage: `url(${require(`../../../assets/images/${card.img}`)})`
}}
></div>
</div>
))}
It looks like inside the map I can't get name or img for every card ?? And when I console log "cards", it show me the JSON like above with name and img properties
Assuming your code is wrapped in a function component (see below), it may be an issue with how you're importing / using cards.json. Also in the useEffect, make the dependency array [] instead of [cards]. I changed your code to this and it works:
import React, { useEffect, useState } from "react";
import cardsJson from "./cards.json";
export function Cards() {
const [cards, setCards] = useState();
useEffect(() => {
console.log(cardsJson);
setCards(cardsJson.cards);
}, []);
return (
<div>
{
cards &&
cards.map((card, index) => (
<div key={card.name} className="cardHero">
<div className="front">{card.name}</div>
<div
className="back"
></div>
</div>
))
}
</div>
);
}
Note I put the cards.json in the same folder as the Cards component, I'm not outputting the image and I updated the dependency array.
If you only want to display the cards there is no reason for them to be inside a useEffect. I recommend you to create a constant and initialize it with cardsJson.cards, like:
const cards = cardsJson.cards;
Or if you want to play with states, just initialize your state with cardsJson.cards, like:
const [cards, setCards] = useState(cardsJson.cards);

How to show first letters of the firstname and lastname of the user in the list instead of image through json data using reactjs

I'm new to reactjs, doing a small react app which should hold first letter of User's firstname and lastname using json data in reactjs. but i'm unable to do it... I getting functions for static data but not for dynamic.
json data:
[
{
"id": 1,
"firstname": "Avelino",
"lastname": "Cajes",
"position": ".Net Developer",
},
{
"id": 2,
"firstname": "Nilson",
"lastname": "Audrey",
"position": "C#",
}
]
Can anyone help me to do this problem? Thanks in advance.
I want in this way
Install react-avatar:
npm install react-avatar
Then try adapting this code to suit your use case
import React from "react";
import Avatar from 'react-avatar';
let data = [
{ "id": 1, "firstname": "Avelino", "lastname": "Cajes", "position": ".Net Developer"},
{ "id": 2, "firstname": "Nilson", "lastname": "Audrey", "position": "C#", }
]
class MyComponent extends React.Component{
state = {data}
render(){
return(
<div>
{ this.state.data.map(item=>(
<Avatar name={item.firstname+" "+item.lastname} maxInitials={2}/>
))
}
</div>
)
}
}
You can find out more on how to use react-avatar here
I think this is what u asked for
pass this to text element: firstName.charAt(0).toUpperCase() +""+lastName.charAt(0).toUpperCase()
import { LinearGradient } from 'expo-linear-gradient';
<LinearGradient colors={['#4c669f', '#3b5998', '#192f6a']} style=
{styles.linearGradient}>
<Text style={styles.buttonText}>
</Text>
</LinearGradient>
// Later on in your styles..
var styles = StyleSheet.create({
linearGradient: {
flex: 1,
paddingLeft: 15,
paddingRight: 15,
borderRadius: 5
},
buttonText: {
fontSize: 18,
fontFamily: 'Gill Sans',
textAlign: 'center',
margin: 10,
color: '#ffffff',
backgroundColor: 'transparent',
},
});

Getting "No applicable renderer found" when using React and JSONSchema Form

I'm learning React and decided to check out JSON Forms ( https://jsonforms.io/docs/tutorial ).
I can get the seed app from https://github.com/eclipsesource/jsonforms-react-seed running, and I also experimented with moving all the form-related stuff into its own component, instead of putting it all in index.js. That works great in the seed app.
Then I decided to try to set up the demo form from the playground schema ( https://mozilla-services.github.io/react-jsonschema-form/ ) in the seed app, just to make sure I knew how to change a form.
This is where the wheels came off. Instead of a form, I get "No applicable renderer found."
I copied the three inputs in the playground ( schema, UISchema, and formData ). Below is the code from the separate component, with the schema, uischema, and data taken directly from the playground data jsonschema provides:
import { JsonForms } from '#jsonforms/react';
import React from 'react';
import { combineReducers, createStore } from 'redux';
import { Provider } from 'react-redux';
import { Actions, jsonformsReducer } from '#jsonforms/core';
import { materialFields, materialRenderers } from '#jsonforms/material-renderers';
const data = {
firstName: "Chuck",
lastName: "Norris",
age: 75,
bio: "Roundhouse kicking asses since 1940",
password: "noneed"
};
const schema = {
"title": "A registration form",
"description": "A simple form example.",
"type": "object",
"required": [
"firstName",
"lastName"
],
"properties": {
"firstName": {
"type": "string",
"title": "First name"
},
"lastName": {
"type": "string",
"title": "Last name"
},
"age": {
"type": "integer",
"title": "Age"
},
"bio": {
"type": "string",
"title": "Bio"
},
"password": {
"type": "string",
"title": "Password",
"minLength": 3
},
"telephone": {
"type": "string",
"title": "Telephone",
"minLength": 10
}
}
};
const uischema = {
"firstName": {
"ui:autofocus": true,
"ui:emptyValue": ""
},
"lastName": {
"ui:autofocus": true,
"ui:emptyValue": ""
},
"age": {
"ui:widget": "updown",
"ui:title": "Age of person",
"ui:description": "(earthian year)"
},
"bio": {
"ui:widget": "textarea"
},
"password": {
"ui:widget": "password",
"ui:help": "Hint: Make it strong!"
},
"telephone": {
"ui:options": {
"inputType": "tel"
}
}
};
const store = createStore(
combineReducers({ jsonforms: jsonformsReducer() }),
{
jsonforms: {
fields: materialFields,
renderers: materialRenderers
},
}
);
store.dispatch(Actions.init(data, schema, uischema));
function SampleForm() {
return (
<div>
<Provider store={store}>
<JsonForms />
</Provider>
</div>);
}
export default SampleForm;
index.js looks like this:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(
<App />,
document.getElementById('root')
);
registerServiceWorker();
and finally, the app itself, App.js, looks like this:
import React from 'react';
import './App.css';
import SampleForm from './sampleform';
const styles = {
container: {
padding: '1em'
},
title: {
textAlign: 'center',
padding: '0.25em'
},
dataContent: {
display: 'flex',
justifyContent: 'center',
borderRadius: '0.25em',
backgroundColor: '#cecece',
},
demoform: {
margin: 'auto'
}
};
const App = () => (
<div>
<SampleForm/>
</div>
);
export default App;
<JsonForms
schema={schema}
uischema={Generate.uiSchema(schema)}
data={data}
renderers={materialRenderers}
/>
https://github.com/eclipsesource/jsonforms/issues/923#issuecomment-374936319

Right way to parse Redux state props - using super json objects

Following my trip with React and Redux, I'm facing a problem, simple in appearance, but hard to solve : I'm setting my Redux state with a very big JSON object. Those datas are retrieved from an async call. When I'm setting it, I created an entry in my reducer with
let initialState = {
pages: []
}
Then, I'm putting different pages, with their params and datas into this pagesarray. So far so good, the state is well updated.
BUT, my different app pages use only parts of it as you can imagine. For instance, I have a page named Gallery which might need my state to look like this :
"pages": [
{
"component":"Gallery",
"key": "gallery",
"title": "Galerie photos",
"url": "/galerie-photos",
"sections": [
{
"component": "Gallery",
"params": {
"images": [
{
"id": 1,
"src": "http://lorempicsum.com/futurama/627/300/1",
"alt": "alternate text"
},
{
"id": 2,
"src": "http://lorempicsum.com/futurama/500/400/2",
"alt": "alternate text"
},
{
"id": 3,
"src": "http://lorempicsum.com/futurama/400/320/3",
"alt": "alternate text"
},
{
"id": 4,
"src": "http://lorempicsum.com/futurama/800/500/4",
"alt": "alternate text"
},
{
"id": 5,
"src": "http://lorempicsum.com/futurama/320/300/5",
"alt": "alternate text"
},
{
"id": 6,
"src": "http://lorempicsum.com/futurama/420/360/6",
"alt": "alternate text"
}
]
}
}
]
}
]
In my GalleryContainer, I'm requesting only the images property as this is the only concern of my Gallery component. I'm able to retrieve this data with no problem. Testing with the following code returns the desired images array :
But as far as I tested this, the images are not retrieved by my Gallerycomponent : when console logging on the component side, I got undefined, and on the container side, no problem.
I tested something different : I set a galleryImages property via the reducer, and set it with the gallery images directly. This worked.
The questions are : Why doesn't it work in the first case, and do in the second ? Do I have to work only with datas that are set as state properties only ? Can't I have a "super" json set in my state to work with directly ?
Thanks to light me up on this one :)
// Component
import React from 'react'
const Gallery = ({images}) => (
<div>
{images.map((image, key) =>
<div key={key} className="image-element-class" style={card}>
<img src={image.src} alt={image.alt} style={imageStyle}/>
</div>
)}
</div>
)
const card = {
width: 'calc((100% / 3) - (15px / 1.5))',
marginBottom: '15px',
boxSizing: 'border-box'
}
const imageStyle = {
width: '100%'
}
export default Gallery
// Container
import { connect } from 'react-redux'
import Gallery from '../../components/pages/Gallery'
const getImages = state => {
return {
images: state.data.pages.filter(page => page.component === 'Gallery' &&(
page.sections.filter(section => section.component === 'Gallery' &&(
section.params.images
))
)),
}
}
const mapStateToProps = state => {
return getImages(state)
}
const GalleryContainer = connect(
mapStateToProps,
{}
)(Gallery)
export default GalleryContainer
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.2/react-dom.min.js"></script>

Resources