I'm working on a React project that takes input from two select boxes, queries an external JSON file for values, and maps the result using Mapbox. My code is structured as a single file without Redux since I need a fairly quick turnaround and I can't wrap my head around how to use Redux. So far, I have gotten the program to map values with the initial state. However, I'm having issues updating the map when the values in the select boxes change. Code within my class is as follows:
class VID extends React.Component {
constructor(props, context) {
super(props, context);
this.handleChange = this.handleChange.bind(this);
this.state = {
//Set initial state. This works.
};
}
componentDidMount(){
const mapConfig = {
//map configuration
};
mapboxgl.accessToken = 'token';
const map = new mapboxgl.Map(mapConfig);
//Loop through dataset. Find records meeting a criteria. Push to array.
//This works fine.
var arr = [];
Object.keys(Data).forEach(function(key) {
if (//filtering criteria are met) {
arr.push(Data[key]);
};
});
//Define layers for each matching record.
Object.keys(arr).forEach(function(key) {
map.on('load', function() {
map.addLayer({
"id": key,
"type": "circle",
"source": {
"type": "geojson",
"data": {
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [arr[key].LONG, arr[key].LAT]
},
}
},
"paint": {
'circle-radius': //formula to set radius based on count,
'circle-color': '#000000'
}
});
})
})
}
//SOMEWHERE INSIDE THIS HANDLECHANGE BLOCK LIES MY PROBLEM
handleChange(e) {
this.setState({
//Set state based on values of select boxes. This works.
},
function(){
//Same as before. Create an array of matching records.
var arr = [];
Object.keys(Data).forEach(function(key) {
if (//new filtering criteria are met) {
arr.push(Data[key]);
};
});
Object.keys(arr).forEach(function(key) {
map.setPaintProperty(key, 'circle-radius', //formula)
});
})
}
render() {
return (
//All of my JSX
)
}
When I run the above code, I receive the following error in my web console: TypeError: map.setPaintProperty is not a function. My web page also crashes (goes from showing my user interface to a blank white page).
I have tried a few other remedies:
* Using this.map.setPaintProperty (TypeError: this is undefined)
* Trying other life cycle methods like componentWillReceiveProps and shouldComponentUpdate (code doesn't execute when I change options in the select boxes -- confirmed with console.log)
* Defining the map inside the class but outside of the life cycle methods (Module build failed: SyntaxError: Unexpected token)
* Defining the map outside of the class (Error: Container 'map' not found.)
How would I have to structure my code so that I can get the circle sizes to update?
If it helps, I'm running react 16.2.0 with mapbox-gl 0.44.0