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;
}
CodePudding user response:
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>
)