Search code examples
javascriptreactjstypesmaterial-uionchange

Material-UI Rating returns string instead of number


I am running into a problem with the Material UI rating component.

I want it to return a number when I change it, but it returns a string. The initial value I provide (this.props.data.feelings_rating) is a number, but whenever I change it in my app it becomes a string. Here is the relevant code:

Rating component:

<Rating
          value={this.props.data.feelings_rating}
          name="feelings_rating"
          onChange={handleChange}
          size="large"
          getLabelText={(value) => customIcons[value].label}
          IconContainerComponent={IconContainer}
        />

handleChange:

handleChange = (e) => {
    var diary = this.state.diary
    diary[e.name] = e.value
    this.setState({diary: diary})
  }

other stuff to do with the icons:

const customIcons = {
  1: {
    icon: <SentimentVeryDissatisfiedIcon />,
    label: 'Very Dissatisfied',
  },
  2: {
    icon: <SentimentDissatisfiedIcon />,
    label: 'Dissatisfied',
  },
  3: {
    icon: <SentimentSatisfiedIcon />,
    label: 'Neutral',
  },
  4: {
    icon: <SentimentSatisfiedAltIcon />,
    label: 'Satisfied',
  },
  5: {
    icon: <SentimentVerySatisfiedIcon />,
    label: 'Very Satisfied',
  },
};

function IconContainer(props) {
  const { value, ...other } = props;
  return <span {...other}>{customIcons[value].icon}</span>;
}

IconContainer.propTypes = {
  value: PropTypes.number.isRequired,
};

I cannot find anyone else on the internet with this problem, so can anyone spot what I am doing wrong? Any answers would be appreciated.


Solution

  • The onChange of the Rating component gives you 2 arguments one is the event object and the other is actual value. You can retrive the selected value from the second argument newValue

    handleChange = (e, newValue) => {
        // create a copy of the state
        const clonedDiary = {...this.state.diary}
        // now mutate the clonedDiary directly
        clonedDiary[e.name] = newValue;
        this.setState({diary: clonedDiary })
     }
    

    Refer

    Rating API