0

When I tried to pass a number as argument to function inside JSX the above error occured.

Working file Link : https://codesandbox.io/s/divine-hill-v3gl3?fontsize=14&hidenavigation=1&theme=dark&file=/new.js

React Component.


function Rating(data) {
  // This function indent to display number 0 to 3 based on 'data'; 
  switch (data) {
    case data <= 0: {
      return <div>0</div>;
    }
    case 0 < data <= 1: {
      return <div>1</div>;
    }
    case 1 < data <= 2: {
      return <div>2</div>;
    }
    case 2 < data <= 3: {
      return <div>3</div>;
    }
    default:
      return data;
  }
}

function some() {
  return (
    <div>
      <Rating data={product.totalrating} />
    </div>
  );
}

export default some;

2
  • The example you provided works. Can this question be marked as resolved? Commented Jul 14, 2020 at 9:36
  • Thanks, can you please provide me the code ? Commented Jul 14, 2020 at 9:38

3 Answers 3

2

You are using the prop object instead the actual data:

// not Rating(data), 
// as the argument of function component is a prop object
function Rating({data}) {
  //...
  return data;
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you , please note that there is error in switch function, it returns default value instead of comparison. codesandbox.io/s/…
Your switch statement is wrong, I pretty sure you can't use boolean expression there.
Oh I see,I did't know that
Yes you should.
|
1

The problem you get is here:

function Rating(data) {

In a component you are receiving PROPS so you are getting an object like this:

data: {
 data: 1
}

In your code you are comparing with the object so you get the default case in the switch, returning the object above.

to fix it you can do:

function Rating({data}) {

or

function Rating(props) {

and use props.data for your comparations.

Comments

1

When you pass props to the component, you receive them as object. If you pass

<Rating data={data} />

then you receive props in a Rating component like { data: YOUR DATA }

Link to working sandbox https://codesandbox.io/s/fancy-smoke-wl8he

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.