Home > Back-end >  How to set up a conditional required attribute in an input inside a component? Reactjs / Nextjs
How to set up a conditional required attribute in an input inside a component? Reactjs / Nextjs

Time:07-28

I Have a simple component that wraps the label and the input together. I need like in every form, to some inputs to be required and others to not, but you can't pass a parameter to the required attribute, so you can't give it a true or false. And it gets always the attribute.

This is the component:

function Input({ type, name, placeholder, required }) {

    return (
        <div className="inputContainer">
            <input placeholder={placeholder} type={type} name={name} required={required ? 'true' : 'false'} />
            <label htmlFor={name}>{placeholder}</label>
        </div>
    )
}

And this is the calling:

<Input type='text' name='Name' placeholder='Name' required={false} />

What is the best way to solve this?

CodePudding user response:

Possibly something like this?

You can try and render one of two different inputs depending on your required prop, which are almost identical except for one not having the required attirbute

function Input({ type, name, placeholder, required }) {

    return (
        <div className="inputContainer">
            {required ? <input placeholder={placeholder} type={type} name={name} required /> : <input placeholder={placeholder} type={type} name={name}/>}
            <label htmlFor={name}>{placeholder}</label>
        </div>
    )
}

Also if you set the required attribute equal to a boolean, and not a string it should work

function Input({ type, name, placeholder, required }) {

    return (
        <div className="inputContainer">
            <input placeholder={placeholder} type={type} name={name} required={required} /> 
            <label htmlFor={name}>{placeholder}</label>
        </div>
    )
}
  • Related