Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to set up a conditional required attribute in an input inside a component? Reactjs / Nextjs

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

What is the best way to solve this?

>Solution :

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>
    )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading