venter venter - 2 months ago 6
React JSX Question

How to disable a buttonLink in React?

I'm new to React and got a issue to disable a link covert by a button element.

I tried the following:

class ShoppingCartLink extends React.Component {

constructor(){
super();
ShoppingCartStore.register(this.refresh.bind(this));

this.state = {count:0};
this.item = "items";
this.linkDisabled = new Boolean(true);
}

refresh(){
if (ShoppingCartStore.items.length === 0 || ShoppingCartStore.items.length > 1 )
{
this.item = "items";
}
else
{
this.item = "item";
}

if (ShoppingCartStore.items.length !== 0)
{
this.linkDisabled = false;
}

this.setState({count: ShoppingCartStore.items.length});
}

render() {
return (
<div>
<button type="button" disabled = {this.linkDisabled}>
<Link to="shoppingCart">Shopping Cart: {this.state.count} {this.item}</Link>
</button>
</div>
)
}
}


By default the Link should be disbaled as long no item is added to the cart.
I debugged through it and when the constructor is called "linkDisabled" is set to true as well in render(). The problem is that the link is still enabled.

Thanks for your help!

Answer
constructor(){
   super();
   ShoppingCartStore.register(this.refresh.bind(this));

   this.state = {
     count:0,
     linkDisabled: true
   };
}

handleClick(event) {
   if(this.state.linkDisabled) event.preventDefault();
}

refresh(){

   const length = ShoppingCartStore.items.length;

   this.setState({
      count: length,
      linkDisabled: (length === 0)
   });
}

render() {
   const length = ShoppingCartStore.items.length;
   return (<div>
            <Link to="shoppingCart"
                  onClick={this.handleClick.bind(this)}>Shopping Cart: {this.state.count} {((length > 0)?"items":"item")}</Link>
    </div>);
}

After some refactoring ... Try this ?