Home > Mobile >  Printing state value in React which is boolean doesn't get printed by String Interpolation
Printing state value in React which is boolean doesn't get printed by String Interpolation

Time:12-22

import React, { Component } from 'react';

class ButtonStatus1 extends Component {

  constructor(props){
    super(props);
    this.state = {
      a: "false",
      b: false
    }
  }

  render(){
    return (
      <div>
        <h1>a: {this.state.a}, b: {this.state.b}</h1>
      </div>
    );
  }
}

export default ButtonStatus1;

Output:

enter image description here

Expected:

false, false

String Interpolation, as far as I know, will always output in form of string, whatever the input is. So, in that scenario, even if this.state.b was a boolean - false, the output should have been printed. If the value is there -- just because it was boolean, why is it not printed. Isn't this strange??

CodePudding user response:

{} is not just string interpolation

It is a JSX syntax to inform that the expression inside it needs to be evaluated

But there are some specific values for which nothing will be rendered, like

<div />

<div></div>

<div>{false}</div>

<div>{null}</div>

<div>{undefined}</div>

<div>{true}</div>

and booleans are often used for conditional rendering like

{array.length > 0 && array.map(...)}

if array.length > 0 is false, rendering false is not desirable

React docs


btw, you can convert the booleans to strings if you want to render them (false.toString())

CodePudding user response:

JSX is executing an expression inside of {}, it's not string interpolation.

If React DID print booleans/nulls/undefined, it would mean you could not do short circuits like:

isTrue() && <p>hello world</p>

Instead of rendering nothing if isTrue() equals false, it would always render false in the DOM. This would make conditional rendering much more cumbersome.

CodePudding user response:

Into React world return false has the same result as return null. So string interpolation it is simple function that return NOT only strings. It can be any rendered JSX component. That's why false rendered as empty value. You should use

String(this.state.b);
  • Related