Reputation: 15404
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?
Upvotes: 0
Views: 1308
Reputation: 954
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" >
Upvotes: 0
Reputation: 5529
You can try another way
return (
<Button disabled ={disabled} variant="outlined" color="primary" >
Start
</Button>
Upvotes: 0
Reputation: 1036
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' : '';
Upvotes: 2