Search code examples
javascriptreactjswebreact-component

React Component : "if else" statement not updating inside return statement


I am noob in React and pretty new in front.

I am trying to change the color of the property "fill" (in polygon) in React. If perc > 50 i want the result to be green, and otherwise red.

I have written an "if else" statement but no color is rendering.

I have checked this Is it possible to use if...else... statement in React render function? and other sources online/ What i want to do seems possible and i don't know why its not rendering.

import React, { Component } from 'react';

class SvgStationIconGauge extends Component {
  render() {
    const { perc } = this.props || 0;
    const color_fill = 0;
    if (perc >50) {
      color_fill = "#ff0000";
    } else {
      color_fill = "#00ff00";
    }
    return (
      <svg xmlns="http://www.w3.org/2000/svg" width="100%" height="100%" viewBox="0 0 50 120" className="icon-station">
        <title>Station name</title>
        <desc>Marker with gauge to display availability </desc>
     //#Here is what i am trying to render!!
        <polygon points="2 2 48 2 48 80 25 118 2 80" stroke="#333333" strokeWidth="4" fill= {color_fill} />
        <clipPath id="fill-icon">
          <polygon points="4 4 46 4 46 80 25 116 4 80 " strokeWidth="1" />
        </clipPath>
        <g clipPath="url(#fill-icon)">
          <rect width="100%" height={perc} fill="white" />
        </g>
      </svg>
    );
  }
}

export default SvgStationIconGauge;

As mentionned, i am a noob in React and any observation or suggestion would be welcomed!


Solution

  • you can't ressign const. use let

    let color_fill = 0;
        if (perc >50) {
          color_fill = "#ff0000";
        } else {
          color_fill = "#00ff00";
        }