简体   繁体   中英

React htmlFor - clicking label focus on the wrong input

I have the following code:

const SomeComponent = () => {
return (
    <div>
            <label className={styles.label} htmlFor="firstName">
              First Name
            </label>
            <input type="text" id="firstName" value={user.firstName} />
          </div>
          <div>
            <label className={styles.label} htmlFor="lastName">
              Last Name
            </label>
            <input type="text" id="lastName" value={user.lastName} />
          </div>
          <div>
            <label className={styles.label} htmlFor="email">
              Email
            </label>
            <input type="email" id="email" value={user.email} />
          </div>);
    }

which is rendered in multiple places on the same page. Clicking on the label of an element in the middle always creates focus on the first input, and not the input near it.

How I can make sure the label focuses on the right input (The one near it, which is in the same component) and not the first one (the first SomeComponent which was rendered)?

You have to make sure that ids are unique across the whole page. So looks like you have several inputs using the id email And that is why the first input in the page gets the focus.

One way to fix it would be to pass the id To the component as props.


const SomeComponent = ({id}) => {
  
  return (
    <div>
            <label className={styles.label} htmlFor={`firstName-${id}`}>
              First Name
            </label>
            <input type="text" id= {`firstName-${id}`} value={user.firstName} />
          </div>
          <div>
            <label className={styles.label} htmlFor= {`lastName-${id}`} >
              Last Name
            </label>
            <input type="text" id= {`lastName-${id}`} value={user.lastName} />
          </div>
          <div>
            <label className={styles.label} htmlFor= {`email-${id}`} >
              Email
            </label>
            <input type="email" id= {`email-${id}`} value={user.email} />
          </div>);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM