State element does not appear on react simple map with react-tooltip - json

The code is working with the property 'name', names appear correctly on the map.
I wanted to enrich the json file with datas coming from my mysql database (like, add the name of countries in french or spanish for example).
I added a state 'countries' which will be initialized with json file converted in object. I fetch data from my sql database and then I set the state 'countries' with data I wanted to add.
Here is the code :
import React, { Component } from "react"
import {
ComposableMap,
ZoomableGroup,
Geographies,
Geography,
} from "react-simple-maps"
import ReactTooltip from "react-tooltip"
import jsonWorldMap from "./maps/world-50m.json"
const wrapperStyles = {
width: "100%",
height: "100%",
backgroundColor: "#0565A1"
}
class WorldMap extends Component {
constructor(){
super()
this.state = {
zoom: 1,
color: "#39464E",
countries: jsonWorldMap
}
}
componentDidMount() {
//get all countries in db
fetch('http://localhost:3001/countries')
.then(res => res.json())
.then(body =>
body.data.forEach(function(elementSql){
jsonWorldMap.objects.units.geometries.forEach(function(elementJson){
if(elementSql.alpha3 == elementJson.id)
{
elementJson.properties.nameFr = elementSql.name_fr;
}
})
})
)
this.setState({ countries: jsonWorldMap }, () => console.log(this.state.countries))
}
render() {
return (
<div style={wrapperStyles}>
<ComposableMap>
<ZoomableGroup center={[0,20]}>
<Geographies geography={this.state.countries}>
{(geographies, projection) => geographies.map((geography, i) => geography.id !== "ATA" && (
<Geography
className="Geography"
key={i}
data-tip={geography.properties.nameFr}
geography={geography}
projection={projection}
/>
))}
</Geographies>
</ZoomableGroup>
</ComposableMap>
<ReactTooltip />
</div>
)
}
}
export default WorldMap
So you can see that I added a component to have a console.log at the end of the component. See what console.log gives :
So you can see that the property 'nameFr' is present in the state object 'countries'. But, If I try to display it as tooltip, it doesn't work. And it works perfectly with property 'name' (in data-tip)

If data-tip={geography.properties.name} works fine but data-tip={geography.properties.nameFr} does not, then it seems that the problem is with state.
See your componentDidMount method. You are updating state with jsonWorldMap at the end of this method.
But as fetch is async , at that moment jsonWorldMap may not be updated yet. So I think you should move that line inside fetch. please see below:
componentDidMount() {
const _this = this; // hold this inside _this
//get all countries in db
fetch('http://localhost:3001/countries')
.then(res => res.json())
.then(body => {
body.data.forEach(function(elementSql){
jsonWorldMap.objects.units.geometries.forEach(function(elementJson){
if(elementSql.alpha3 == elementJson.id)
{
elementJson.properties.nameFr = elementSql.name_fr;
}
})
});
_this.setState({ countries: jsonWorldMap }, () => console.log(this.state.countries)); //making sure setting updated jsonWorldMap to state
}
)
}
hope it helps.
thanks

Wrap Geography with an element that uses data-tip as a props.
<div data-tip={geography.properties.nameFr}>
<Geography ... />
</div>
In order to <Geography data-tip={props.nameFr}/> work, Geography component need to use the data-tip property internaly, something like:
function Geography(props) {
return <h1 data-tip={props['data-tip']}>I'm a map</h1>;
}
To solve your problem you need to attach data-tip property to Geography wrapper, for example:
function Geography(props) {
return <h1>I'm a map</h1>;
}
function ComponentWithTooltip({ props }) {
return (
<div data-tip="nameFr">
<Geography />
</div>
);
}
function App() {
return (
<>
<Geography data-tip="hello-world" /> // Your way, won't work
<ComponentWithTooltip /> // Work
<div data-tip="nameFr2"> // Work
<Geography />
</div>
// Works with div wrapper, without won't work.
{geographies.map((geofraphy, i) => (
<div key={i} data-tip={geofraphy.properties.nameFr}>
<Geography />
</div>
))}
<ReactTooltip />
</>
);
}
Check out the demo with all use cases:

Related

How do you loop through json with map and filter in React?

I have data in json format and I want to loop through it to render the same component (ContentThumbnail) eight times but with different titles and other content.
I have tried creating a function which accepts four parameters to achieve this. Here is the function I've written in a separate file called RenderContent.js:
import React from 'react';
import ContentThumbnail from './ContentThumbnail';
function RenderContentThumbnail(data, sectionName, wrapperStart, wrapperEnd) {
return (
<div>
{data
.filter(d => d.sectionName === { sectionName })
.map(filteredSection => (
{wrapperStart}
<ContentThumbnail {filteredSection.title} />
{wrapperEnd}
))}
</div>
);
}
export default RenderContentThumbnail;
And here is where I'm trying to execute that function in my component DefaultDashboard.js:
import React, { useEffect } from 'react';
import RenderContent from '../../content-thumbnail/RenderContent';
const DefaultDashboard = () => {
const { data } = useFetchData({ queryString: `${contentLibraryApiUrl}/GetContentForPage/Home` });
return (
RenderContentThumbnail(data, "topSection", "<div>", "</div>")
);
};
export default DefaultDashboard;
Is anyone able to help me see where I'm going wrong? I'm getting errors inside my map function and the page won't render at all.:(
Many thanks!
Katie
UPDATE!
I have made a tweak to the code to specify the prop, which is called "title", but I'm getting the following:
You should change the way you are rendering RenderContent:
const DefaultDashboard = () => {
const { data } = useFetchData({ queryString: `${contentLibraryApiUrl}/GetContentForPage/Home` });
return (
<RenderContent data={data} sectionName="topSection" wrapperStart="<div>" wrapperEnd= "</div>")
);
};
You can make it a lot easier, removing RenderContentThumbnail:
const DefaultDashboard = () => {
const { data } = useFetchData({ queryString: `${contentLibraryApiUrl}/GetContentForPage/Home` });
return (
{data
.filter(d => d.sectionName === "topSection")
.map(filteredSection => (<div>
<ContentThumbnail title={filteredSection.title} />
</div>))
}
);
};
export default DefaultDashboard;

Trouble getting into json data object

I have some code that allows the user to click a image to then update the page and display the clicked on champions name. the json data looks like this -http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion/Alistar.json
I console.log response.data and see a object of objects and am wondering how to get passed the section that has the response.data.(whatever champion the user picked). I have tried adding a variable like response.data.champion but I assume no variables can be passed like that seeing how it doesnt work.
Not sure if its even worth posting the code but just in case! My code is below, the fetch im trying to go through is in NewChamp function.
To make my request simpler, All i want to know for example is how i would get response.data.(whatever the user clicked).key from any possible champion clicked like http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion/Alistar.json or http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion/Anivia.json
or whatever other champion the user clicks.
import React, { Component } from 'react';
import './Champions.css';
class AllChamps extends Component {
render() {
let champion = this.props.champion;
return(
<div className='champions'>
<h1> all champions</h1>
{Object.keys(this.props.champions).map((s) => (
<div className='champs' onClick={() => this.props.NewChamp({s, champion})}>
<img
alt='Champion Images'
src={`http://ddragon.leagueoflegends.com/cdn/10.16.1/img/champion/${s}.png`}
onClick={this.props.onClick}
></img>
{s}
</div>
))}
</div>
)}}
class SpecificChamp extends Component {
render() {
let champion = this.props.champion
let Spec = champion[champion.length - 1];
return (
<div className='champions'>
<h1> 1 champions</h1>
<div className='champs'>
<button onClick={this.props.onClick}></button>
{Spec}
</div>
</div>
)}
}
class Champions extends Component {
constructor(props) {
super(props);
this.handleAllChamps = this.handleAllChamps.bind(this);
this.handleSpecificChamp = this.handleSpecificChamp.bind(this);
this.NewChamp = this.NewChamp.bind(this);
this.state = {
champions: [],
champion: [],
clickedChamp: false,
thisChamp: 'ahri'
}}
NewChamp = (props) =>
{
let s = props.s;
props.champion.push(s);
fetch(`http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion/${s}.json`)
.then(response => { return response.json() })
.then((response) => {
Object.keys(response.data).map((a) => (s = a
))})
fetch(`http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion/${s}.json`)
.then(response => { return response.json() })
.then((response) => {
console.log(s)
console.log(response.data)
console.log(props.champion)
})
console.log(`http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion/${s}.json`);
}
handleAllChamps = (props) => {
this.setState({ clickedChamp: true,
})};
handleSpecificChamp = () => {
this.setState({ clickedChamp: false,
})};
componentDidMount(props) {
const apiUrl = `http://ddragon.leagueoflegends.com/cdn/10.16.1/data/en_US/champion.json`;
fetch(apiUrl)
.then(response => { return response.json() })
.then((response) => {
this.setState({
champions: response.data
}, () => (this.state.champions))
return
})
}
render() {
const clickedChamp = this.state.clickedChamp;
let display;
if (clickedChamp ) {
display = <SpecificChamp champion={this.state.champion} onClick={this.handleSpecificChamp} s={this.state.thisChamp}/>;
} else {
display = <AllChamps champions={this.state.champions} onClick={this.handleAllChamps} NewChamp={this.NewChamp} thisChamp={this.state.thisChamp} champion={this.state.champion} />;
}
return (
<div>
<div className='champions'></div>
{display}
</div>
);
}
}
export default Champions;
Your response is in the form of Object of Objects. You've to use JSON.stringify(response.data) in order to view the entire data as a string in the debug console.
You will have to destructure the Object of objects.
Object.keys(response.data).map((key)=> console.log(response.data[key]))
In this case if it is just one key
response.data[s]

React rendering JSON nested objects

I have this code which works perfectly:
componentDidMount() {
fetch('https://services2.arcgis.com/sJvSsHKKEOKRemAr/arcgis/rest/services/Bigfoot%20Locations/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json')
.then((response) => {
return response.json();
})
.then((myJson) => {
this.setState({data: myJson.features[0].attributes.STATE_NAME})
console.log(this.state.data)
});
}
render() {
return (
<div className = ''>
{this.state.data}
</div>
)
}
}
However when I try to make the data set in state more general so that I can render whatever I want like this:
componentDidMount() {
fetch('https://services2.arcgis.com/sJvSsHKKEOKRemAr/arcgis/rest/services/Bigfoot%20Locations/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json')
.then((response) => {
return response.json();
})
.then((myJson) => {
this.setState({data: myJson.features})
console.log(this.state.data)
});
}
render() {
return (
<div className = ''>
{this.state.data[0].attributes.STATE_NAME}
</div>
)
}
}
I get "Cannot read property STATE_NAME of undefined. The only change is that I tried to access the object in the render method instead of ComponentDidMount. What's the issue here?
In your component, the render() function is being called before the data is populated, even though componentDidMount() will run before the first render.
What you need is to store an intermediate loading state in your react state to indicate that the data has not yet arrived.
class RENAME_ME extends Component {
state = {
loaded: false,
data: [],
};
componentDidMount() {
fetch(
"https://services2.arcgis.com/sJvSsHKKEOKRemAr/arcgis/rest/services/Bigfoot%20Locations/FeatureServer/0/query?where=1%3D1&outFields=*&outSR=4326&f=json"
)
.then((response) => {
return response.json();
})
.then((myJson) => {
this.setState({
data: myJson.features[0].attributes.STATE_NAME,
loaded: true,
});
console.log(this.state.data);
});
}
render() {
// Data is still loading, display an intermediate message
if (!this.state.loaded) {
return <p>Loading...</p>;
}
return <div className="">{this.state.data}</div>;
}
}
You shouldn't read from the state until it's present:
render() {
return (
<div className = ''>
{(this.state.data && this.state.data.length) ? this.state.data[0].attributes.STATE_NAME : `still loading, or maybe an error`}
</div>
)
}
Only display the state when it is present so this condition has 2 parts.
First part(this.state.data) is only true when the data is saved in the state so the next part(this.state.data[0].attributes.STATE_NAME) runs after that
render() {
return (
<div className = ''>
{this.state.data && this.state.data[0].attributes.STATE_NAME}
</div>
)
}
}
Your state 'data' is not properly initialized to handle object maybe
are they initialized like this?
this.state = {
data: []
You can render the value whenever it is present by
{this.state.data[0].attributes && this.state.data[0].attributes.STATE_NAME}

React-native: how to get JSON from backend and put the objects in react-native elements, such as Text?

I am trying to fetch JSON data from a php file, which seems to work fine; I can alert values from the JSON. But I want to be able to put these values on the mobile app screen in Text elements or whatever. And I want this to happen when the screen opens, not when a button is pressed. So I made a function that fetches the JSON and I'm trying to return a value in Text elements. This function is called from the rendering. I don't get error messages, but it isn't working. Nothing shows up.
Here is the code:
import React, { Component } from 'react';
import { View, Text, AsyncStorage, Alert } from 'react-native';
import { UsersMap } from '../UsersMap';
import { PrimaryButton } from '../Buttons';
import styles from './styles';
class RestOptions extends Component {
getSearchResults() {
fetch('http://192.168.1.3/Restaurant_App/php/search_results.php')
.then((response) => response.json())
.then((responseJson) => {
var JSON_Test = responseJson["distance"][0];
//Alert.alert(JSON_Test);
return (
<View>
<Text>{JSON_Test}</Text>
</View>
);
}).catch((error) => {
console.error(error);
});
}
setReservation = () => {
this.props.navigation.navigate('SetReservation');
};
render() {
return (
<View>
<UsersMap />
{this.getSearchResults()}
<PrimaryButton
label="Set Reservation"
onPress={() => this.setReservation()}
/>
</View>
);
}
};
export default RestOptions;
This is what happens. The JSON value should appear between the map and the button:
Search Results Screen
First of all, in order to fetch the data as the screen opens, you should use the lifecycle method componentWillMount, which executes before the first render, and then store the result in the component's state. React docs on state and lifecycle
class RestOptions extends Component {
constructor(props) {
super(props);
this.state = {
jsonTest: null
}
}
componentWillMount() {
this.getSearchResults();
}
getSearchResults() {
fetch('http://192.168.1.3/Restaurant_App/php/search_results.php')
.then((response) => response.json())
.then((responseJson) => {
var JSON_Test = responseJson["distance"][0];
//Alert.alert(JSON_Test);
this.setState({ jsonTest: JSON_Test });
}).catch((error) => {
console.error(error);
});
}
//...
Then you can display the value on the render() method:
render() {
return (
<View>
<UsersMap />
<Text>{this.state.jsonTest}</Text>
<PrimaryButton
label="Set Reservation"
onPress={() => this.setReservation()}
/>
</View>
);
}
If the response is an array of values, you can use map() to display each of them in their own Text element:
{this.state.jsonTest.map((value, index) => <Text key={index}>{value}</Text>)}

How to use React SetState on nested data with empty top level names?

I have the following JSON data:
[
{"ID":1,"Latitude":"-41.276253","Longitude":"173.283842","Image":"Church.jpg"},
{"ID":2,"Latitude":"-41.267783","Longitude":"173.279114","Image":"Centre.jpg"}
]
I am trying to import it so it can be rendered & started with the following code:
componentDidMount() {
fetch('/home/briefsJson').then(response => response.json()).then(data => {
console.log(data);
this.setState({
latitude: data.Latitude,
longitude: data.Longitude,
image: data.Image
});
});
}
This doesn't as the data is multidimensional/nested. But every example I've found is using better structured data with top level names.
How can I use setState & render to display this data?
If you want to import json from a js file you would do it like this.
Data.js
const Data = [
{"ID":1,"Latitude":"-41.276253","Longitude":"173.283842","Image":"Church.jpg"},
{"ID":2,"Latitude":"-41.267783","Longitude":"173.279114","Image":"Centre.jpg"}
]
export default Data
Then import it where you want to use it. Now you can map through the data as you like.
App.js
import Data from './data'
import React, {Component} from 'react'
class App extends Component {
state = { Data:[] }
componentDidMount() { this.setState({ Data: Data }) }
render() {
return(
<div> {this.state.Data.map(item => <div> The id is: {item.ID} </div> }</div>
)
}
}
Maybe you want to change the names of the items, and return a new data structure with less attributes this is how you would do it.
componentDidMount() {
fetch('/home/briefsJson').then(response => response.json()).then(data => {
const newData = data.map(item => {
latitude:item.Latitude,
longitude: item.Longitude,
image: item.Image}
}
this.setState({
Data:newData
});
});
}
Now if you want to display this data in render.
renderData = () => {
return (
<div>
{this.state.Data.map(item => (
<div>
{item.latitude}
{item.longitude}
<img src={item.img} />
</div>
)}
</div>
)
}
render() {
return (
<div> {this.renderData()} </div>
)
}
It would probably just be easier to first construct what you want, then do a mapping in the rendering. It looks like you don't even need to do anything to convert it, since the json data is exactly what you want in the first place. So:
componentDidMount() {
fetch('/home/briefsJson').then(response => response.json()).then(data => {
console.log(data);
this.setState({ data });
});
}
render() {
return (
<div>
{this.state.data.map(datum => (element))}
</div>
);
}