0

I am new to React and TypeScript. I want to set an attribute if a prop is true (boolean).

I am using Material UI's button, which can take disabled prop, eg <Button disabled>Disabled</Button>.

I have the following:

interface sectionProps {
  title: string;
  disabled?: boolean;
}

const Section = ({
  title,
  disabled,
}: sectionProps) => {

  const isDisabled = {disabled ? 'disabled' : ''};

  return (
    <Button {isDisabled} variant="outlined" color="primary" >
      Start
    </Button>
  )
};

But I get an error on compilation where it seems to want to replace the ? in the ternary with a ,. I don't understand this.

Unexpected token, expected ","

Would anyone be able to point me in the right direction?

3 Answers 3

2

This isn't an error with typescript, the error indicates an error with your javascript syntax. You're wrapping your ternary expression in curly braces, causing JS to think you're trying to define an object, hence why it's looking for a ,.

Change that line to this:

const isDisabled = disabled ? 'disabled' : '';
Sign up to request clarification or add additional context in comments.

Comments

0

Change

const isDisabled = {disabled ? 'disabled' : ''};

to

const isDisabled = disabled ? 'disabled' : '';

Also:

Change

<Button {isDisabled} variant="outlined" color="primary" >

to

<Button disabled={isDisabled} variant="outlined" color="primary" >

Comments

0

You can try another way

return (
  <Button disabled ={disabled} variant="outlined" color="primary" >
     Start
  </Button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.