Search code examples
reactjsconditional-rendering

React conditional rendering is not giving the expected value (it is not working)


I am trying to disable a button if the array length is > 0 and if the array length is equal to zero it need to show the button (without disable)

I tried conditional rendering for that like this.

                   {this.state.aboutus.map((item) => (
                        (this.state.aboutus.length > 0 ?
                            <button type="button" className="btn btn-info" style={{ float: 'right', padding: '12px 28px', marginBottom: '30px' }} disabled={true}>
                                <PlusLg /> Add About Us Details
                            </button>
                            :

                            <button type="button" className="btn btn-info" style={{ float: 'right', padding: '12px 28px', marginBottom: '30px' }} onClick={() => { window.location.href = APP_ROUTES.ADMIN_ADD_ABOUT_US }}>
                                <PlusLg /> Add About Us Details
                            </button>
                        )
                    ))}

In here if the this.state.aboutus.lenght is > 0 I want to disable the button and otherwise it doesn't need to disable. But when I use this code and even if there is no data in the database is is not showing the button. But if there is one data the but is disabled.

I don't know what is wrong in this coding. Please help.


Solution

  • In this function,

    (item) => (
                        (this.state.aboutus.length > 0 ?
                            <button type="button" className="btn btn-info" style={{ float: 'right', padding: '12px 28px', marginBottom: '30px' }} disabled={true}>
                                <PlusLg /> Add About Us Details
                            </button>
                            :
    
                            <button type="button" className="btn btn-info" style={{ float: 'right', padding: '12px 28px', marginBottom: '30px' }} onClick={() => { window.location.href = APP_ROUTES.ADMIN_ADD_ABOUT_US }}>
                                <PlusLg /> Add About Us Details
                            </button>
                        )
    

    there is no reference to the item, so you don't need to use map:

    When the array is empty, map never runs, so your button is never rendered.

    To solve the issue, simply omit map:

    <div>{
      (this.state.aboutus.length > 0 ?
          <button type="button" className="btn btn-info" style={{ float: 'right', padding: '12px 28px', marginBottom: '30px' }} disabled={true}>
              <PlusLg /> Add About Us Details
          </button>
          :
    
          <button type="button" className="btn btn-info" style={{ float: 'right', padding: '12px 28px', marginBottom: '30px' }} onClick={() => { window.location.href = APP_ROUTES.ADMIN_ADD_ABOUT_US }}>
              <PlusLg /> Add About Us Details
          </button>
      )
    }</div>