Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

305
Visualizações
React JS Legacy code described as `hacky`, why would the author state this?

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);

    })
}
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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>;
}
about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda