Jason Chen Jason Chen - 4 months ago 9
Javascript Question

call React class with a variable string?

This example uses Reactjs and Datamaps.

I am making a tool that is supposed to select states from a map. A portion of that code is below.

datamap.svg.selectAll('.datamaps-subunit.MI').on('click', function(){
var state = 'mi';
if (sting.state.mi === 'und'){
sting.setState({trumpnums: sting.state.trumpnums + sting.state.miv, mi: 'right'});
map.updateChoropleth({MI:'red'});
datamap.svg.selectAll('.datamaps-subunit.MI').on('mouseout', function(){
map.updateChoropleth({MI:'red'});
});
}
});


To save me from having to repeat a lot of this for each state, I was hoping to store my React classname in a variable.

All instances of
MI
and
mi
refer to Michigan. So, I was hoping that instead of having to type
sting.state.mi
, I was hoping for something like

var state = 'mi';
if (sting.state.{state} === 'und'){//rest of my code}


I already set a placeholder for
var state
as you can see in the code above. However, it does not work with my React class.

Answer

JavaScript bracket notation:

if (sting.state[state] === 'und')