React - setting the required attribute of an <input> element based on a prop value

37 Views Asked by At

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?

1

There are 1 best solutions below

0
hersh On BEST ANSWER

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 } : {})} works

The expression {...(isRequired ? { required: true } : {})} works because in the case of isRequired being true, this expression spreads a key-value pair (which is what JSX expects), and in the case isRequired is false it spreads an empty object which is a valid syntax and doesn't add the required attribute to the input

The more idiomatic solution for this would be to directly assign the isRequired prop to the required input attribute as following

required={isRequired}