sai pavan
sai pavan

Reputation: 37

how to control tab key between buttons in react, javascript?

I have 3 buttons Cancel, Back, Continue respectively. when press tab key that should be going to Continue, Cancel, Back buttons.
How can we do that in React, Javascript? Please refer https://codesandbox.io/s/crazy-ishizaka-cnr5k?file=/src/App.js

export default function App() {
  return (
    <div className="App">
      <button tabIndex="2">submit 1</button>
      <button tabIndex="3">submit 2</button>
      <button tabIndex="1">submit 3</button>
    </div>
  );
}

this above code is'nt working as I expected. Please suggest efficient solution for this.

Upvotes: 0

Views: 4325

Answers (1)

Shayan Faghani
Shayan Faghani

Reputation: 240

The first thing about the tabIndex is it would act weird for use if you want to jump directly to the buttons and inputs. After some researches about your problem, I have found out you have to do two things:

  1. The first one is you have to add all:initial to the root in your project style. for example in your case that the project is React, you have to add this to the index.html and change that like this:

<!DOCTYPE html>
<html lang="en" style="all: initial;">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="theme-color" content="#000000" />

    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />

    <title>React App</title>
  </head>

  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>

  </body>
</html>

I have changed the HTML tag and added the style in the second line

  1. the second thing that you have to d is that you need to consider a side for the buttons that the index can go through it at first and then it can follow your order. in my case, I have added this: (and know that the first tab would do nothing)

export default function App() {
  return (
    <div className="App" tabIndex={1}>
      <button tabIndex={3}>submit 1</button>
      <button tabIndex={4}>submit 2</button>
      <button tabIndex={2}>submit 3</button>
    </div>
  );

I have forked your codesandbox and you can access it with this link: https://codesandbox.io/s/dawn-hill-1br66?file=/src/App.js

Upvotes: 1

Related Questions