Usurper
Usurper

Reputation: 97

React Button disabled property not working on conditionals

I have a DIV which contain two child element. These elements are button and I want to add disabled property to these buttons on some conditions, when I apply conditions to these buttons it's not working. I don't know why this is not working although conditions are correct.

My code is as follows :

< div className = 'change-page' >
  <
  button
type = 'button'
disabled = {
  page === 0 ? 'true' : ''
}
onClick = {
    () => setPage(page > 1 ? page - 1 : 1)
  } >
  Prev <
  /button>

  <
  button
type = 'button'
onClick = {
  () => setPage(page + 1)
}
disabled = {
    next === 1 ? '' : 'true'
  } >
  Next <
  /button> <
  /div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>

Here page === 0 means user is at the first page so, prev button should be disabled, same goes for next button if there is not next page available than this next button should disabled.

Please suggest a possible solution to this problem.

Upvotes: 1

Views: 793

Answers (3)

RiTeSh
RiTeSh

Reputation: 531

You set start page from 0, when page === 2 then set page returning 1. and when page ===1 then , prev button assign 1 to the *page

  () => setPage(page > 1 ? page - 1 : 1)

Here is my working code.

import React, { useState } from 'react';

const MyComponent = () => {

  const [page, setPage] = useState(1); // Starting from page 1
  const [next, setNext] = useState(1);
  return (
    <div className='change-page' >
      Page: {page} <br />
      Next: {next} <br />
      <button
        type='button'
        disabled={page === 1} // If page == 1 then disabled Button
        onClick={
          () => setPage(page > 1 ? page - 1 : 1)
        } >Prev </button>

      <button
        type='button'
        onClick={
          () => setPage(page + 1) // On next increment the page
        }
        disabled={next === 1 ? false : true} >
        Next </button>
    </div>
  )
}
export default MyComponent;

Upvotes: 1

Sergey Pogodin
Sergey Pogodin

Reputation: 416

This: () => setPage(page > 1 ? page - 1 : 1) suggests your page indices are 1-based, thus page is never 0. Not sure, what exactly is next value, but disabling Next button when next equals some specific number also looks suspicious.

Upvotes: 1

FireFighter
FireFighter

Reputation: 706

Try returning a boolean instead of a string:

disabled={page === 0}

Upvotes: 0

Related Questions