Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: setting the disabled attribute based on a state

I'd like to set the disabled attribute on a Button based on component's state, something like this:

render() {   return (     <button type="button" {this.state.submitting ? 'disabled' : ''}        onClick={ this.handleSubmit }>Submit</button>     ); } 

At the moment I get an Unexpected token error on the opening {, what am I missing?

like image 355
jolyonruss Avatar asked Nov 12 '15 14:11

jolyonruss


People also ask

How do you disable input in React based on condition?

To disable an input field inside a <Form /> function component, we will use isDisabled local state and it's setter method setIsDisabled , defined using the useState() hook.

What is enable and disable button based on condition in React?

Use the disabled prop to disable a button in React, e.g. <button disabled={true}>Click</button> . You can use the prop to conditionally disable the button based on the value of an input field or another variable or to prevent multiple clicks to the button. Copied!

How do I change state properties in React?

To update nested properties in a state object in React: Pass a function to setState to get access to the current state object. Use the spread syntax (...) to create a shallow copy of the object and the nested properties. Override the properties you need to update.


2 Answers

You can set disabled property through boolean value, like this

<button   type="button"   disabled={this.state.submitting}   onClick={this.handleSubmit} >   Submit </button> 

Example

like image 102
Oleksandr T. Avatar answered Oct 09 '22 11:10

Oleksandr T.


You could use null

<button type='button' disabled={this.state.submitting ? 'disabled' : null} onClick={this.handleSubmit}>Submit</button> 
like image 24
Ol' Dawg Avatar answered Oct 09 '22 12:10

Ol' Dawg