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>
    );
}

>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>
    );
}

Leave a Reply