Home > Back-end >  How can I implement this HTML/JavaScript 'URL generator' into a React app?
How can I implement this HTML/JavaScript 'URL generator' into a React app?

Time:03-17

I have a simple React boilerplate app with the basic components you would find in such an app. I am after a function for my react app that is able to take several URLs and from that generate one which can be passed into the simple "onClick" in react or even as part of "href". I am unsure how to achieve this because onClick expects a function and even when I create a function, my function generates and returns a string URL which onClick does not accept.

Example I found for HTML/CSS/JS:

var urlArray = [
    "http://www.google.com",
    "http://www.yahoo.com",
    "http://www.stackoverflow.com"
];

function randomUrl() {
    var randomNumber = Math.floor(Math.random() * urlArray.length);
    var newUrl = urlArray[randomNumber];
    window.location.href = newUrl;
}

<a href="#" onclick="randomUrl();" target="_blank"><img id="img-hover" src="image"/></a>

CodePudding user response:

  1. Remove the onClick
  2. set the anchor's href to a variable, e.g. randomUrl.
  3. make the randomUrl variable stateful so it's remembered across renders.
  4. set the state variable in useEffect()

See if you can do that...

It should look like this (I typed this 'live' so there may be syntax error):

const MyComponent = () => {
  const [randomUrl, setRandomUrl] = useState()

  useState(()=>{
    function getRandomUrl() {
      var urlArray = [
        "http://www.google.com",
        "http://www.yahoo.com",
        "http://www.stackoverflow.com"
      ];
      const randomNumber = Math.floor(Math.random() * urlArray.length);
      const newUrl = urlArray[randomNumber];
      return newUrl;
    }
    setRandomUrl(getRandomUrl())
  },[])

  return (
    <a href={randomUrl} target="_blank"><img id="img-hover" src="image"/></a>
  )
}

CodePudding user response:

The default behaviour of anchor tag is to refresh the page, so even before you can see it it's rendering it immediately . You have 2 options

  1. Loose the href property from your anchor tag. Or use href='javascript:void(0)'
  2. Prevent the default behaviour by suppressing the event. event.preventDefault() in your click handler.
  • Related