Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between if(x) and if(x==true) in a reactjs component

When I was writing the ReactJs code below, I first used if(this.state.username==true) and did not get the result I expected. But When I used if(this.state.username) it worked as I needed. Therefore, I can obviously see that there is a difference between if(x==true) and if(x). I also know that sometimes, they can mean the same and produce the same result. My question is if my constructor is set up as below, why would the two expressions behave differently. What is the true meaning of if(this.state.username) here? Thanks for helping me understand.

  constructor(props){
    super(props)
    this.state = {username:""}
  }

The two codes are below:

class MyForm extends React.Component {
  constructor(props){
    super(props)
    this.state = {username:""}
  }
  changeName = (e) =>{
    let target = e.target;
    let name   = target.name; 
      let value  = target.value;
    this.setState ({[name]: value});
  }
  render(){
    let myHeader;
    if(this.state.username==true){
        myHeader = <h1>Hello {this.state.username}</h1>;
    }else{
        myHeader = "";
    }
    return (
      <form>
        {myHeader}
        <h1>{this.state.username}</h1>
        <p>Enter your name:</p>
        <input
          name='username'
          type="text"
          onChange = {this.changeName}
        />
      </form>
    );
  }
}   
ReactDOM.render(<MyForm />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>


<div id="root"></div>

And

class MyForm extends React.Component {
  constructor(props){
    super(props)
    this.state = {username:""}
  }
  changeName = (e) =>{
    let target = e.target;
    let name   = target.name; 
      let value  = target.value;
    this.setState ({[name]: value});
  }
  render(){
    let myHeader;
    if(this.state.username){
        myHeader = <h1>Hello {this.state.username}</h1>;
    }else{
        myHeader = "";
    }
    return (
      <form>
        {myHeader}
        <h1>{this.state.username}</h1>
        <p>Enter your name:</p>
        <input
          name='username'
          type="text"
          onChange = {this.changeName}
        />
      </form>
    );
  }
}   
ReactDOM.render(<MyForm />, document.getElementById('root'));
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>


<div id="root"></div>
like image 652
ITselect Avatar asked Dec 22 '21 02:12

ITselect


People also ask

Can you use if statements in React JSX?

if-else statements don't work inside JSX. This is because JSX is just syntactic sugar for function calls and object construction. We can't use if-else statement or any other statement directly inside JSX, only expressions are allowed.

How do you render two components conditionally in React?

Use a ternary operator to conditionally render multiple elements in React. When returning multiple sibling elements, make sure to wrap them in a React fragment. Copied! We used a ternary operator to conditionally render multiple elements.

How compare two values in react JS?

We can use the comparison operator to compare two strings in JavaScript. In this example, we are using the triple equals (===) comparison operator instead of double equals (==) to avoid the type coercion. The triple equals (===) operator only returns true when both values and types are same otherwise it returns false.


2 Answers

if (expr) would be considered true if the expr is "truthy".

'<str>' == true expression would be considered true if <str> equals '1'.

In your case it probably makes more sense to do

if (this.state.username !== '') {

References:

  • https://tc39.es/ecma262/#sec-equality-operators
  • https://tc39.es/ecma262/#sec-islooselyequal
like image 97
zerkms Avatar answered Oct 20 '22 01:10

zerkms


There's a difference between using if(this.state.username==true) and if(this.state.username). Using the former compares the value of this.state.username with true, which of course is false unless it returns a string value of 1, in which case it will return true.
However, doing the latter casts this.state.username to boolean and checks if this.state.username has a value (like not undefined).
So if you want to use if(this.state.username==true), you will have to cast this.state.username to boolean first by using !! (or Boolean):

if(!!this.state.username==true) {
  // your code goes here
}
like image 2
Capt 171 Avatar answered Oct 20 '22 02:10

Capt 171