简体   繁体   中英

React - How can I redirect to another page after some conditions are met on the OnClick of a Button?

So in this component, I have a button called Submit which when clicked will do the following operations: it will export the drawing that the user has made as a jpeg url, pass it to another api that returns an image caption, then compares this image caption to a string prompt that was returned prior. I would like to redirect the user to another webpage based on whether the comparison between the image caption and the prompt was the same or not. How would I go about this?

 <button onClick={() => { let W = this.handleWord() let valid = this.state.valid this.canvas.current.exportImage("jpeg").then(imagedata => { fetch('https://hf.space/embed/Salesforce/BLIP/+/api/predict/', { method: "POST", body: JSON.stringify({"data":[imagedata,"Image Captioning","None","Beam Sampling"]}), headers: { "Content-Type": "application/json" } }).then(function(response) { return response.json(); }).then(function(json_response) {blip = json_response.data valid = blip.includes(W) //blip which is a string returned by the api above is checked to see if W is in the string console.log(valid) //based on this valid boolean, i want to have page be redirected to either Success or Share, two seperate pages ive made }) }).catch(e => { console.log(e); }); }} className='buttonprops'> <img src={submitbutton} width = {120} height = {35} alt = 'Submit!' /> </button>

const YourComponent = () => {
  // if you're using react-router...
  const navigate = useNavigate(); // import { useNavigate } from 'react-router-dom'

  const handleClick = () => {
   // your button click logic...
   navigate(valid ? "/success" : "/share")

   // or if you're not using react-router...
   window.location.pathname = valid ? "/success" : "/share"
  }

  return <button onClick={handleClick}>click me</button>
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM