Warm tip: This article is reproduced from serverfault.com, please click

React router Link to conditionally render button

发布于 2020-12-21 16:59:14

I have a button with an onclick that takes it to a function which displays an alert asking "are you sure". If the person clicks ok on the alert, I would like the link to go to a certain page. If they click cancel, I would like it to go to a different page. Here is what I have...

        <Link to="/calibrateAir" params={{ moisture: props.moisture }}>
            <MyButton onClick={() => {calibrateAgain()}}>
                Calibrate Again
            </MyButton>
        </Link>

and the function...

function calibrateAgain() {
    const user = localStorage.getItem('user')
    const alertWindow = window.confirm("Are you sure you want to calibrate?")
    if (alertWindow) {
        axios.post("http://localhost:3001/api/calibrate", 
        {airValue: null, waterValue: null, user: user}).then((response) => {
            alert(response.data)
        }, (error) => {
            console.log(error)
        })
    }
}

Basically I want to render "/calibrateAir" if alertwindow is true else "/".

Questioner
Justin Oberle
Viewed
0
jean182 2020-12-22 01:24:59

Don't use a link component, use react router history to accomplish what you want. For example if you are using a functional component you can do

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

 export default function YourComponent() {
  const history = useHistory()

  function calibrateAgain() {
   const user = localStorage.getItem('user')
   const alertWindow = window.confirm("Are you sure you want to calibrate?")
   if (alertWindow) {
    axios.post("http://localhost:3001/api/calibrate", 
    {airValue: null, waterValue: null, user: user}).then((response) => {          
        // Push to the calibrateAir if response succeeds
        history.push("/calibrateAir");
        alert(response.data)
     }, (error) => {
        // Push to the / if response fails
        history.push("/");
        console.log(error)
     })
    } else {
      // Push to the / if user press cancel in the alert
      history.push("/");
    }
  }

  return (
    <MyButton onClick={calibrateAgain}>
      Calibrate Again
    </MyButton>
 );
 }