简体   繁体   中英

NextJS: How to keep button active?

I have 3 buttons in a group and a form. When I select a button it stays active which is correct behaviour. However if I click "submit" on the form, the previously selected button is not active anymore. How do I keep the button active even after submitting the form? I'm using NextJS and css styles.

const [position, setPosition] = useState("");
const categoryOptions = ["Left", "Middle", "Right"];

return (
  <div className={styles.card}>
      {categoryOptions.map((category) => (
          <button
            type="button"
            className={styles.buttonGroup}
            onClick={() => setPosition(category)}
          >
            {category}
          </button>
        ))}
      <form className={styles.form} onSubmit={someFunction}>
        <label htmlFor="amount">Amount</label>
        <input
          id={props.id}
          name="amount"
          type="number"
          required
        />
        <button className={styles.button} type="submit">
          Submit amount
        </button>
      </form>
  </div>
)

here is the css for buttons

.buttonGroup {
  color: #000000;
  border-radius: 0px;
  border: 0px;
  min-width: 80px;
  min-height: 30px;
}

.buttonGroup:hover {
  color: red;
}
.buttonGroup:focus,
.buttonGroup:active {
  color: red;
  font-weight: bold;
}

You can call useRef to keep your active element, and then call focus to regain your previous button focus state. For example

const [position, setPosition] = useState("");
const categoryOptions = ["Left", "Middle", "Right"];
const currentCategoryRef = useRef()

return (
  <div className={styles.card}>
      {categoryOptions.map((category) => (
          <button
            type="button"
            className={styles.buttonGroup}
            onClick={(event) => { 
               setPosition(category) 
               currentCategoryRef.current = event.target //set current active button
            }}
          >
            {category}
          </button>
        ))}
      <form className={styles.form} onSubmit={someFunction}>
        <label htmlFor="amount">Amount</label>
        <input
          id={props.id}
          name="amount"
          type="number"
          required
        />
        <button className={styles.button} type="submit" onClick={() => {
           setTimeout(() => currentCategoryRef.current && currentCategoryRef.current.focus()) //focus back to the previous button in categories
        }}>
          Submit amount
        </button>
      </form>
  </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