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

Using form labels for multiple elements

My page has many js-generated form elements which can exist simultaneously but need to be created from the same block of code (jsx, react). My problem is that I need to give labels to all these form elements for semantics and seo, but I can’t give them all the same id (becuase html ids are unique). Is the only option to dynamically generate unique html ids? Is there any way to do this with html classes?

My code would look something like this:

function cardEditor() {
    return (
        <form>
            <label for="card-title">Title: </label>
            <input type="text" id="card-title">
            <button type="submit">Save</button>
        </form>
    );
}

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

>Solution :

You can pass id as props to your component

const Input = ({ id }) => {
    return <>
       <label for={id}>Title: </label>
       <input type="text" id={id}>
    </>
}
function cardEditor() {
    return (
        <form>
            <Input id="card-title-1" />
            <Input id="card-title-2" />
            <Input id="card-title-3" />
            <button type="submit">Save</button>
        </form>
    );
}

or generate unique ids for your form elements

const uuid = () => Math.random().toString(36).slice(-6);

const Input = () => {
    const id = uuid();
    return <>
       <label for={id}>Title: </label>
       <input type="text" id={id}>
    </>
}

function cardEditor() {
    return (
        <form>
            <Input/>
            <Input/>
            <Input/>
            <button type="submit">Save</button>
        </form>
    );
}
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