Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Can i disable <Link href="" /> in next JS on various conditions

My Code is That : <Link href={/blog/${bdetails.id - 1}}> Prev Post <Link href={/blog/${bdetails.id + 1}}> Next Post

Question

I want to navigate to next post or previous post on condition.

Explanation

I have an array of blogData in my [id].js and achieving bdetails.id by using props to my this component which is BlogDetailContent.js . I want to control previous and next post by simple disabling previous button on bdetails.id === 1 , here button should be disabled. I want it by simple ternary operator or by if condition. I do not want to use next/router . It should be using by function component not by class component.

like image 544
Muhammad Sibtain Avatar asked Nov 25 '25 20:11

Muhammad Sibtain


1 Answers

For Nextjs 12+

You need to add the following depending on that condition

  1. pointer-event: none to disable mouse events.
  2. aria-disabled="true" to give the screen readers insight that the link is disabled.
  3. tabIndex="-1" to disable keyboard navigation.

Using CSS

css

.disabled {
  pointer-events: none
}

jsx

<Link 
  href='/link' 
  className={someCondition ? 'disabled': ''} 
  aria-disabled={someCondition} 
  tabIndex={someCondition ? -1 : undefined}
>Link</Link>

Using TailwindCSS

jsx

<Link 
  href='/link' 
  className={someCondition ? 'pointer-events-none' : ''} 
  aria-disabled={someCondition} 
  tabIndex={someCondition ? -1 : undefined}
>Link</Link>

Using Inline style

jsx

<Link 
  href='/link' 
  style={
    'pointer-event' someCondition ? 'none' : 'auto'
  } 
  aria-disabled={someCondition} 
  tabIndex={someCondition ? -1 : undefined}
>Link</Link>

Old answer for Older versions

You need to add an a tag inside the Link tag and just use a class that gives pointer-events: none; for the element and conditionally add or remove this class.

<Link 
  href='/link' 
  passHref>
  <a className={someCondition ? 'disabled' : ''}>Link</a>
</Link>

CSS

.disabled{
  pointer-events: none;
}
like image 171
Mina Avatar answered Nov 27 '25 08:11

Mina



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!