NewTech Lover
NewTech Lover

Reputation: 1263

What is wrong in this react useState hook?

I found this component online which creates a review component but it's not working.

import { useState } from 'react';

const Star = ({filled, starId}) => (
  <span star-id={starId} style={{ color: '#ff9933' }} role="button">
  {filled ? '\u2605' : '\u2606'}
</span>
);

export const Rating = props => (
  const [rating, setRating] = useState(typeof props.rating == 'number' ? props.rating : 0);
  const [selection, setSelection] = useState(0);
  const hoverOver = event => {
    let val = 0;
    if (event && event.target && event.target.getAttribute('star-id'))
      val = event.target.getAttribute('star-id');
    setSelection(val);
  };
  return (
    <div
      onMouseOut={() => hoverOver(null)}
      onClick={event => setRating(event.target.getAttribute('star-id') || rating)}
      onMouseOver={hoverOver}
    >
      {Array.from({ length: 5 }, (v, i) => (
        <Star
          starId={i + 1}
          key={`star_${i + 1} `}
          filled={selection ? selection >= i + 1 : rating >= i + 1}
        />
      ))}
    </div>
  );

It throws an error for this line:

 const [rating, setRating] = useState(typeof props.rating == 'number' ? props.rating : 0);

What is wrong with it? And how can be it fixed?

Upvotes: 0

Views: 104

Answers (1)

Giraphi
Giraphi

Reputation: 1651

I think the hook is fine, but you need to use {} around the function body:

export const Rating = props => {
    const [rating, setRating] = useState((typeof props.rating === 'number') ? props.rating : 0);
    const [selection, setSelection] = useState(0);
    const hoverOver = event => {
        let val = 0;
        if (event && event.target && event.target.getAttribute('star-id'))
            val = event.target.getAttribute('star-id');
        setSelection(val);
    };
    return (
        <div
        onMouseOut={() => hoverOver(null)}
        onClick={event => setRating(event.target.getAttribute('star-id') || rating)}
        onMouseOver={hoverOver}
        >
            {Array.from({ length: 5 }, (v, i) => (
            <Star
            starId={i + 1}
            key={`star_${i + 1} `}
            filled={selection ? selection >= i + 1 : rating >= i + 1}
            />
            ))}
        </div>
    );
};

codesandbox

A second thing you should consider: You probably should use === instead of == for the typeof check.

Upvotes: 2

Related Questions