Sudhir Jangam
Sudhir Jangam

Reputation: 766

ReactJS ternary operator with boolean props

I am trying to use ternary operator with a boolean props

The app.js is as follows :

import React from 'react';
import  HouseFull  from './HouseFull';

function App() {
  return (
    <div>
    <h1> Hello2 </h1>
    <HouseFull hasOpening="{false}" />


    </div>
    
  );
}

The react component is as follows

import React, { Component } from 'react';

class HouseFull extends Component {

    render() {
        return (
            <div>
                 
                <h1> {this.props.hasOpening} </h1>
                <h1> {this.props.hasOpening ? "Available" : "No Vacancy"} </h1>
                
            </div>
        )

    }

}

export default HouseFull;

The result of the second h1 tag is the same, if I pass hasOpening as true or false If I pass true, following is displayed

{true}
available

If I pass false, following is displayed

{false}
available

I am suspecting something is wrong in the statement with the ternary operator, but cannot figure out. The value of the boolean flag is reflected properly in the first h1 tag in the outpur

Upvotes: 0

Views: 3249

Answers (2)

Md Sabbir Alam
Md Sabbir Alam

Reputation: 5054

You are passing a string as props in . You need to pass boolean.

<HouseFull hasOpening={false} />

Otherwise, you will have to check in the HouseFull component in the following manner,

 <h1> {this.props.hasOpening === "{false}" ? "Available" : "No Vacancy"} </h1>

Upvotes: 2

kind user
kind user

Reputation: 41893

The ternary operator is okey, but you are passing down a string instead of a boolean. Non-empty string will always evaluate to true, that's why nothing happens when you toggle it.

hasOpening={false}

Upvotes: 1

Related Questions