lost9123193 lost9123193 - 27 days ago 14
React JSX Question

Const does not Exist in React

I have the following code in react. The style corresponds to the names of the markers imported at the top.

import {markerColored, markerUnColored, markerDefault} from './markers.js';

....

render() {
if(this.props.colored){
const style = markerColored;
}else if(this.props.unSelected){
const style = markerUnColored;
}else{
const style = markerDefault;
}

return (
<div className=" hint hint--html hint--info hint--top " style={style}>
{this.renderMarkerIcon()}
</div>
);
}
}


When I run the following above, I get the error:

Uncaught ReferenceError: style is not defined


However, if I were to do something like this, I get no error:

render() {

const style = this.props.colored? markerColored : markerUnColored

return (
<div className=" hint hint--html hint--info hint--top " style={style}>
{this.renderMarkerIcon()}
</div>
);


The problem is I have 3 styles I want to use. Why does the top code tell me the const style doesn't exist when it goes through the conditional loops? Is there something trivial I'm missing?

Answer

const are always specific to a scope. Here the scope is if and else. After that it will be undefined.

Try this

let style = markerDefault
if(this.props.colored){
   style = markerColored;
}else if(this.props.unSelected){
   style = markerUnColored;
}
Comments