2

I am new to React.js and I am not sure how to handle this.

I did a selection with react where the selected option is passed by the link. I am also using the react router.

If no option is selected I want to redirect to the first option when the page loads.

function initTrainer() {

    for(let i = 0; i < trainer.length; i++) {
        trainer[i].link = "/trainer/" + trainer[i].firstName.toLowerCase() + "-" + trainer[i].lastName.toLowerCase();
        trainer[i].key = i;
    }

    if(window.location.pathname === "/") {
        // navigate("/trainer/")
    }
}

How can I redirect without a click in a normal function? Is there an easier solution to this problem?

Y I am using React Router V6 but I want to call navigate() conditionally.

ahaMfM
  • 126
  • 11
  • 2
    Does this answer your question? [How to do a redirect to another route with react-router?](https://stackoverflow.com/questions/34735580/how-to-do-a-redirect-to-another-route-with-react-router) – Ricola Jul 17 '22 at 13:06

3 Answers3

2

You can use this code in your component to make it work:

const navigate = useState();

return (
  {() => navigate("/your-path")}
)
Albert
  • 36
  • 2
1

Since you using react-router, you can use <Redirect>.. you can read about react-router Redirect here: React-Router-Redirect

1

When looking at your question, I think you are asking how navigate pragmatically in react. This can be done using react router. But depending on the react router version this is different.

In React Router v4 when you importing import { Route } from 'react-router-dom' your componet getting History object via props.so that you can nvigate,

this.props.history.push('/yourpath')

In React Router V5

You have to import below import statement where you are using the this pragmatically navigation.

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

export default function home() {
  const history = useHistory();

//use this function to navigate
  function handleClick() {
    history.push("/yourpath");
  }


  return (
    <div>home</div>
  )
}

In In React Router V6

import { useNavigate, useParams } from "react-router-dom";

export default function home() {

  const navigate = useNavigate();
  //you can extrat route paramters using useParams hook
  const { id } = useParams();

//use this function to navigate
  function handleClick() {
    navigate("/yourpath");
  }


  return (
    <div>home</div>
  )
}

Additionally If you use next js latest version (V12)

import useRouter hook to your component ,

import { useRouter } from "next/router"; and run the hook inside the component using const router = useRouter();

then you can use router.push("/yourpath") to navigate desired path