I have two buttons in my form and I want them to change style when you clicked on them. Currently, they are like this:
import React from "react";
import { Form } from "react-bootstrap";
import { Link } from "react-router-dom";
export default function InstantQuoteForm () {
return (
<Form className="shadow p-3 mb-5">
<Form.Group controlId="formGroupFrom">
<button type="submit" className="links">
Button1
</button>
<button type="submit" className="links">
Button2
</button>
</Form.Group>
</Form>
);
}
So, when I click one of them I want to add a 'link-selected' style to it. I could do that but I wasn't successful on when I clicked another one, the first one was still with 'link-selected' style. Could you please help me to solve this issue.
.links-selected {
display: inline-block;
background-color: var(--body-color);;
color: var(--second-color);
padding: 0.75rem 1rem;
border-radius: 0;
transition: 0.3s;
border-bottom: solid var(--first-color);
}
First, you can do this way. When the button is focused its style is changed.
.links-selected:focus {
display: inline-block;
background-color: var(--body-color);;
color: var(--second-color);
padding: 0.75rem 1rem;
border-radius: 0;
transition: 0.3s;
border-bottom: solid var(--first-color);
}
Also, you can create a state to preserve the id of the clicked button:
export default function InstantQuoteForm () {
const [clickedButtonId, setClickedButtonId] = useState("");
return (
<Form className="shadow p-3 mb-5">
<Form.Group controlId="formGroupFrom">
<button type="submit" className="links"
onClick={()=>setClickedButtonId("btn1")}
className={`${clickedButtonId === "btn1" && "links-selected"}`}>
Button1
</button>
<button type="submit" className="links"
onClick={()=>setClickedButtonId("btn2")}
className={`${clickedButtonId === "btn2" && "links-selected"}`}>
Button2
</button>
</Form.Group>
</Form>
);
}
Also, you need to prevent the form from submitting by passing this handler to the onSubmit
:
const handleSubmit = (e)=>{
e.preventDefault();
}