Home > Blockchain >  React JS Legacy code described as `hacky`, why would the author state this?
React JS Legacy code described as `hacky`, why would the author state this?

Time:05-22

I have some legacy code from a site that I'm currently working on, and the author added some comments stating that the solution they coded was a bit hacky.

Would anyone know why that would be the case, and why they would have stated that?

    const onClickDownloadFile = (id, filename) => {

    const token = state.token;
    if (token === "") {
        return;
    }

    const req = new Request(process.env.REACT_APP_API_URL 
          "/path/" 
          id 
    );

    fetch(req, {
        headers: new Headers({
            "Authorization": "Bearer "   token,
            "Accept": "application/octet-stream"
        }),
        method: "GET"
    })
    .then(res => res.blob())
    .then((data) => {

    // This is a little hacky but gives a download link the browser will understand
        const url = window.URL.createObjectURL(new Blob([data]));
        const link = document.createElement("a");
        link.href = url;
        link.setAttribute("download", filename);
        document.body.appendChild(link);
        link.click();
        link.parentNode.removeChild(link);

    })
}

CodePudding user response:

This is likely because they are creating a new element in the DOM, then invoking the download attribute, before deleting the element again. Certainly isn’t the best practice but seems to get the job done

CodePudding user response:

Probably backed is not able to send proper HTTP headers like “content-disposition: attachment”. Trying to fix it on UI side we left with code that tries to simulate click on the link so browser will start fetching the resource.

Building link and clicking on it is not related to React self. Author just tried to fix missing contract/agreement between what UI needs and what backend could deliver.

CodePudding user response:

Without reaching the author, we will never know why they deemed it hacky. I deem this code hacky for two reasons:

  1. The code creates a <a> element, sets a link, automatically clicks it, and then deletes it. Manually triggering clicks on elements is very hacky, as we should not take control of the user’s actions. Rather, we should empower them to click elements, instead of our code doing this behind the scenes.

  2. A best practice in React is to not use JavaScript DOM APIs to render HTML. Instead, you read state and props, and use that information to update the HTML your React component renders. This code does not follow this React pattern. Instead it uses DOM APIs to create and remove those elements (such as document.createElement() and document.appendChild() and parentNode.removeChild(). Instead, you would want to see something like the following be added in the render() function of your React class or component:

render() {
  return <a href={someUrl} download>Download your file now<a>;
}
  • Related