I'd like to set the required attribute on the element based on a prop value isRequired that is passed to the component and false by default
Input component:
export default function Input({
name,
id,
type,
labelText,
isRequired=false,
validationFn,
errorMsg,
...props
}) {
return (
<>
<label htmlFor={name} className="font-bold">
{labelText}
</label>
<input
onChange={handleChange}
onBlur={handleBlur}
type={type}
id={id}
name={name}
value={val}
{isRequired && 'required'}
{...props}
/>
</>
);
}
However,
{isRequired && 'required'}
does not work. I'm getting the error:
Unexpected token, expected "..."
I've also tried
{isRequired ? 'required' : ''}
but still the same.
What works is:
{...(isRequired ? { required: true } : {})}
Can someone tell me what the issue is and why the line above works?
Incorrect syntax in first two expressions
{isRequired && 'required'}and{isRequired ? 'required' : ''}throws an error because JSX expects the required (or any other attribute for that matter) to be in a key-value pair format which the above two expressions are not.Why
{...(isRequired ? { required: true } : {})}worksThe expression
{...(isRequired ? { required: true } : {})}works because in the case ofisRequiredbeingtrue, this expression spreads a key-value pair (which is what JSX expects), and in the caseisRequiredisfalseit spreads an empty object which is a valid syntax and doesn't add therequiredattribute to theinputThe more idiomatic solution for this would be to directly assign the
isRequiredprop to therequiredinput attribute as followingrequired={isRequired}