4

What am I doing wrong in this code, I don't know how else to write it I want to test the state invalidForm and render disabled or null depending.

state code UPDATE

if(valid) { return true; } else { this.setState({ invalidForm: true }) } } <button {this.state.invalidForm ? 'disabled' : null} type="submit">Submit</button> 

The Error I am getting is

Unexpected token, expected "..." 
3
  • 1
    it's not HTML, JSX uses an XML syntax, so you need to specify a full attribute="value" string: <button disabled={this.state.invalidForm ? 'disabled' : false} [...] Commented Sep 10, 2018 at 23:29
  • 1
    @Mike'Pomax'Kamermans: That's not quite right: reactjs.org/docs/jsx-in-depth.html#props-default-to-true Commented Sep 10, 2018 at 23:31
  • CHECK YOUR FILE EXTENSION, SHOULD BE .tsx Commented Feb 20, 2021 at 3:01

1 Answer 1

9

While you can define props without a value, you cannot do that dynamically. Pass a value:

<button disabled={this.state.invalidForm}>Submit</button> 

It shouldn't matter, but for clarity, if this.state.invalidForm is not a Boolean value, you can convert it to one:

<button disabled={Boolean(this.state.invalidForm)}>Submit</button> 

Running example:

ReactDOM.render( <div> <button disabled={true}>Button 1</button> <button disabled={false}>Button 2</button> </div>, document.body );
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>


The parser expects ... because the {} syntax inside an opening "tag" is reserved for "spreading" props from objects.

For example:

const props = {disabled: true}; return <button {...props}>Submit</button> 

is the same as

return <button disabled={true}>Submit</button> 
Sign up to request clarification or add additional context in comments.

2 Comments

I added some more code above when the form is invalid it sets a state with a key value of invalidForm:true so how do I remove the disabled when the invalid form is !true
@AndersKitson: It looks like you are not updating the state when the form is valid, so the component doesn't rerender to update the button. Instead of the if ... else statement you should be doing this.setState({invalidForm: !valid});.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.