2

I'm pretty new to Javascript and React, so please bear with me. I have a component in my app, that is taking a timespan from the user, but now I want to calculate the price the user would have to pay, depending on their input. I figured that it would probably be the easiest way to use an if loop but something is very off with that and I am a little stuck.

Is my attempt okay in general or does it need a separate function that I have to call in order to do what I want to do?

 onConfirm(hour, minute) {
    this.setState({ time: `Dauer: ${hour}:${minute}` });
    this.setState(if((hour) < 4){return price = `Preis: (${hour}* 1.5) €`;}
      else {return price= 'Preis: 5.50 €';} );
    this.TimePicker.close();
  }
1
  • 1
    There is no "if loop." if statements aren't loops (loops are things like for, while, etc. -- things that repeat). Commented Dec 15, 2019 at 9:31

1 Answer 1

2

Within an object literal, you can't use statements, only expressions. if is a statement.

If you want to do that either/or logic in an expression, you use the conditional operator (? :), like this:

onConfirm(hour, minute) {
    this.setState({
        time: `Dauer: ${hour}:${minute}`,
        price: hour < 4 ? `Preis: (${hour}* 1.5) €` : 'Preis: 5.50 €'
    });
    this.TimePicker.close();
}

The conditional operator expression in the above is:

hour < 4 ? `Preis: (${hour}* 1.5) €` : 'Preis: 5.50 €'

It's a ternary operator (an operator accepting three operands):

  1. The condition to test (hour < 4)
  2. The expression to evaluate if the condition is truthy¹ (`Preis: (${hour}* 1.5) €`)
  3. The expression to evaluate if the condition is falsy¹ ('Preis: 5.50 €')

Also note you had a closing ' on a template literal (needed a backtick instead).


¹ "truthy" and "falsy" - JavaScript implicitly converts (or coerces) values. When you use a value as a test, such as in an if or a conditional operator, JavaScript converts the value you provide to a boolean value (true or false). Values that convert to true are called "truthy" values, ones that convert to false are called "falsy." The falsy values are NaN, null, undefined, 0, "", and of course false (on browsers, document.all is also falsy for various reasons I explain in my book). All other values are truthy.

Sign up to request clarification or add additional context in comments.

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.