Search code examples
reactjsreact-routeronclickalertconditional-rendering

React router Link to conditionally render button


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 "/".


Solution

  • Don't use a link component(because nesting a button inside an anchor tag is bad html writing), 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>
     );
     }