Bill
Bill

Reputation: 5150

Conditionally autoFocus the first input

I'm generating input fields by mapping over an array but I want just the first input to be auto-focused...

      {keys.map((item, index) => {
        return (
          <div className='poster--keys-values' key={index + 20}>
            <div className='poster--key-title' key={index + 10}>{item}</div>
            <input
              {index === 1 ? 'autoFocus' : null} // <===== This isnt right
              type='text'
              id={item}
              name={item}
              key={index}
              className='poster--value-title'
              onChange={onChange}
            />
          </div>
        );
      })}

Upvotes: 0

Views: 1022

Answers (2)

Max
Max

Reputation: 2036

Instead of

{index === 1 ? 'autoFocus' : null}

write:

autoFocus={index === 1}

Should work as expected

Upvotes: 0

technophyle
technophyle

Reputation: 9149

There is autoFocus attribute, so you can do this:

...
<input
  autoFocus={index === 0}
  ...
/>

Upvotes: 2

Related Questions