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.

1

3 Answers 3

2

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

const navigate = useState();

return (
  {() => navigate("/your-path")}
)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.