I'm updating my Portfolio right now, click.
When I had it checked, I was told that the structure or the tags for each button was not the same and that some areas were not clickable.
Visually, buttons look exactly like buttons when paddings and a border are used or when they're named <Button>
if we use styled-components.
This is very fundamental, but I'll share how to code a clickable button in React.
There are two kinds of buttons: one is "just a button that doesn't do anything itself until we add something to it", and the other is a submit button in a form tag that by default submits the form. I wanted to add a link feature to a button, so I start off with this type of button.
Button with Link
Here's the wrong code.
<div>
<a href="#">
<div>Click</div>
</a>
</div>
I'm using <div>
instead of <button>
inside <a>
. This looks just fine.
The green part is padding I added.
This is an anchor part.
BUT, only this light blue part is clickable. Nothing happens when clicking the white part around it.
Here's the correct code.
<div className="button">
<a href="#">
<button className="label">Click</button>
</a>
</div>
First, it looks like this.
So, delete padding from "button" (css), and add padding
, border: none
, and cursor: pointer
to "label".
Now, it looks like this.
Since the green padding part is now <button>
, the whole area is clickable.
So, simply put, Wrap <button>
with <a>
.
We can replace <a>
with <Link>
(react-router-dom), and it works just fine.
Button in a Form
<form>
<button type="submit">
Submit
</button>
</form>
We just add some styling to the <button>
and the whole area is clickable.
Here's the recap:
- There are two kinds of buttons: "just" a button and a button in a form.
- When adding a link to a button, wrap
<button>
with<a>
. - In
<form>
, just add<button>
and whatever feature we want to do to<form>
such as<form onSubmit={handleSubmit}>
.
Top comments (0)