Cosmin Ciolacu
Cosmin Ciolacu

Reputation: 494

redirect onclick event in react using react-router-dom

I want to go to other pages in my react project using a router-react-dom. I created a function like this:

const {id} = props;
  const redirect = () => {
    console.log("redirecting...");
    const url = `/${id}`;
    return <Redirect to={url} />;
  };

Then I make props to other component like this:

      <BtnDetalii
        clickFn={redirect}
        text="apasa aici pentru mai multe detalii"
      />

and this is my btnDetalii component

const BtnDetalii = props => (
  <div onClick={() => props.clickFn()} className="detalii">
    {props.text}
  </div>
);

When I click the buton doesn't work. What I missed?

Upvotes: 0

Views: 655

Answers (2)

akhtarvahid
akhtarvahid

Reputation: 9779

Check this example for functional component and you can go through documentation for better understanding.

React router dom for functional component

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

Upvotes: 0

gergana
gergana

Reputation: 691

You can use React Router v4. Wrap your component with withRouter from react-router-dom and this way you can access history prop. After that you can push new url to your history prop.

I am not sure what is your code in the parent component where your redirect function is, but this is a simple example using withRouter. If you share more of your component I can change the snippet and add your code.

import React from "react";
import { withRouter } from "react-router-dom";
import BtnDetalii from "./BtnDetalii";

const Card = withRouter(({ history, ...props }) => {
    const redirect = () => {
        console.log("redirecting...");
        const id = props.id;
        const url = `detalii/${id}`;
        history.push(url);
    };
    return (
        <div className="today">
        <div className="data">{props.nume}</div>
        <img src={props.poza} className="img-icon" alt="poza" />
        <p className="text">{props.strada}</p>
        <BtnDetalii
            clickFn={redirect}
            text="apasa aici pentru mai multe detalii"
        />
        </div>
    );
});

export default Card;

Upvotes: 2

Related Questions