Home > Back-end >  React function - change url when page loads
React function - change url when page loads

Time:07-17

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?

CodePudding user response:

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

CodePudding user response:

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

  • Related