0

I have destructed the "password" and "retypepassword" properties from the state, now trying to apply a condition on them. When I am using the if and else statement it's working perfectly fine but when I am using the ternary operator it's not working. I have checked the format of the ternary operator, it's the same as I have written but still not working.

Please let me know what I am doing wrong!

SubmitHandler = e => {
    e.preventDefault();
    const { password, retypepassword } = this.state;
    // if (password === retypepassword) {
    //   console.log("password not match");
    // } else console.log(this.state);
    password === retypepassword
      ? return(console.log("form submitted"))
      : "password does not match";
  };
ProgrammerPer
  • 1,125
  • 1
  • 11
  • 26
Neha Ejaz
  • 55
  • 5
  • You probably are looking for `useState`: https://reactjs.org/docs/hooks-reference.html#usestate – Martijn May 16 '19 at 21:56
  • Could You please also fill up the code with IF example that works for you? – Tatranskymedved May 16 '19 at 21:56
  • 1
    I started to write an answer, but your usage here doesn't make sense. Using a ternary to run `console.log` is an abuse of a ternary. The answer is you need to move the `return` to before the condition (`return password === retypepassword`) but you shouldn't be using a ternary here anyways. Just use an `if` statement. – Carcigenicate May 16 '19 at 21:57
  • 1
    The `return` statement here is only executed in the matching case, and it's returning the result of `console.log`, which is `undefined`. In the non-matching case you're not returning anything. So this handler always returns `undefined`. Perhaps you meant `return password === retyepassword ? 'form submitted' : 'password does not match'`? Not clear what you're trying to do here. – ray May 16 '19 at 22:05
  • Possible duplicate of [Ternary operator with return statements JavaScript](https://stackoverflow.com/questions/19439219/ternary-operator-with-return-statements-javascript) – Code-Apprentice May 16 '19 at 22:09
  • You cannot have a `return` inside a ternary. See the linked question for details. – Code-Apprentice May 16 '19 at 22:09

2 Answers2

4

To match the if/else behavior you'd do:

console.log(password === retypepassword ? "form submitted" : this.state);
ray
  • 26,557
  • 5
  • 28
  • 27
0

The problem is that you have different code in your if/else block than you have in your ternary statement.

See how in your if/else, you are not returning anything, and you are console.log()ing in both conditions?

Just make your ternary operator do the same:

SubmitHandler = e => {
    e.preventDefault();
    const { password, retypepassword } = this.state;

    password === retypepassword 
    ? 
    console.log("form submitted")
    : 
    console.log("password does not match")
  };

But for readability, I don't think ternaries are used this way, even though it technically works.

Maiya
  • 932
  • 2
  • 10
  • 26