skip to Main Content

I am trying to make this button component navigate to different web pages. There will be several buttons, but I am unable to make each one navigate to different pages.

I have the button component that goes to a card component and the card component goes to the page.

What is the best way to make each button in the card go to different pages on web?

Below is the button component

import { Container } from "./styles";

export function Button({ icon, title}){
    return (
        <Container type="button">
            <span>{title}</span>
            <img src={icon} />
        </Container>
    )
}

And here is the card component

export function Card({img, title,desc,tags}){
    return (
        <Container>
            <img src={img} alt="preview site image" />

            <div className="tags">{tags}</div>

            <div className="cont">
                <h2>{title}</h2>
                <p>{desc}</p>
                <div className="btn">
                    <Button 
                        title= {"Live"}
                        icon= {png}
                    />
                    
                </div>
            </div>
            
        </Container>
    )
}

now the component on the page

   <Card 
       img={pomodoro}
       title={""}
       tags={""}
       desc={""}
    />

2

Answers


  1. Are you using Next.js? If so, I recommend using their Link component.

    You can simply wrap your <Button> component inside a <Link> and pass the href prop down to it like this:

    import Link from "next/link";
    import { Container } from "./styles";
    
    export function Button({ icon, title, href }) {
      return (
        <Link href={href}>
          <Container type="button">
            <span>{title}</span>
            <img src={icon} />
          </Container>
        </Link>
      );
    }
    
    
    Login or Signup to reply.
  2. In your Button Component receive which page to navigate.
    If you want to navigate to same web app different page use navigate.

    import { Container } from "./styles";
    import { useNavigate } from 'react-router-dom';
    
    export function Button({ icon, title,linkToNavigate}){
        const navigate = useNavigate();
    
        return (
            <Container type="button" onClick = ()=>{navigate(linkToNavigate)}>
                <span>{title}</span>
                <img src={icon} />
            </Container>
        )
    }
    

    And if you want to navigate to external webapp/website then:

    import { Container } from "./styles";
    
    export function Button({ icon, title,linkToNavigate}){
    
        return (
            <Container type="button" onClick = ()=>{window.location.href=linkToNavigate}>
                <span>{title}</span>
                <img src={icon} />
            </Container>
        )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search