I have a reusable 'button' component and I want to insert a route in one of them to go to another page, I tried putting the <Link> </Link>
but it takes my CSS and the 'button' is small.
It works if I just put it on the text, but it would be really bad to have to click on just the text to take it to another page;
Component Button
import React from 'react';
type ButtonProps = {
style: React.CSSProperties;
children: React.ReactNode;
};
function MouseOver(event: any) {
event.target.style.opacity = '90%'
}
function MouseOut(event: any) {
event.target.style.opacity = ''
}
function Button({ style, children }: ButtonProps) {
return (
<button
onm ouseOver={MouseOver}
onm ouseOut={MouseOut}
style={style}
>
{children}
</button>
)
}
export default Button;
Reusing
<Button
key={id}
style={{
backgroundColor: 'green',
color: 'white',
fontSize: '1.6rem',
borderRadius: '4px',
border: 'none',
display: 'block',
padding: '1rem',
cursor: 'pointer',
fontFamily: '"Roboto", sans-serif',
transition: 'all 0.3s'
}}
>
Create your account
</Button>
CodePudding user response:
You can either wrap your button with a <Link>
and pass the href with a prop:
function Button({ style, children, href }) {
return (
<Link href={href}>
<button
onm ouseOver={MouseOver}
onm ouseOut={MouseOut}
style={style}
>
{children}
</button>
</Link>
)
}
I would abstract this in a <ButtonLink>
component like:
function ButtonLink({ style, children, href}) {
return (
<Link href={href}>
<Button>
{children}
</Button>
</Link>
)
}
Alternatively, you can implement an onClick on the button and do your routing there.
function Button({ style, children, href }) {
const clickHandler = (e) => {
// your redirection logic here (example with history api):
history.push("/some/url")
}
return (
<button
onm ouseOver={MouseOver}
onm ouseOut={MouseOut}
onClick={clickHandler}
style={style}
>
{children}
</button>
)
}
Your implementation here really depends on what API you use for routing/redirecting. In your case it sounds like your <Link>
component is an actual html <a>
tag, since it's changing the style of the children. Make sure you're using a link component from your router library (ex. react-router https://v5.reactrouter.com/web/api/Link)
PS: it's good practice to define methods in the function component's function body, instead of outside of them (see last example).
CodePudding user response:
Link's can be so brutal. Does it have an href="" attribute? Have you tried playing around with that? I think i've usually create buttons with href's and they don't limit the link to just the text.