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

164
Visualizações
"SyntaxError: function statement requires a name" when trying to create onClick event in an element in a template literal

When I run the code below I see different behavior in the sandbox I'm using. When I click the button I get "Uncaught SyntaxError: function statement requires a name" in the console but here it is rendering the click event out as text in the button (not sure why?)

Question is—is there a way to pass functions like this to elements created in template literals that are added to the DOM using innerHTML?

const clickHandler = () => {
  console.log("Hi");
};
const root = document.getElementById("root");
root.innerHTML = `<button onClick=${clickHandler}>Click</button>`;
<!DOCTYPE html>
<html>

<body>
    <div id="root"></div>
</body>

</html>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Inline handlers, being attributes, are essentially strings. When you do

<button onClick=${clickHandler}>

the function gets turned into a string, which results in:

<button onclick="()" ==""> {
  console.log("Hi");
}&gt;Click</button>

which isn't what you want - the automatic fixing of the syntax caused by the interpolation doesn't work well.

When you do it properly, the string in the attribute, when evaluated as JavaScript, may only reference global variables (for all the cases worth mentioning). While you can get your code to work by using the name of the function, and by making sure the function is global:

const clickHandler = () => {
  console.log("Hi");
};
const root = document.getElementById("root");
root.innerHTML = `<button onClick=clickHandler()>Click</button>`;
<div id="root"></div>

A much better approach would be to attach the event listener with JavaScript, instead of an eval-like attribute with scope problems. Insert the elements, then navigate to the element you want the listener attached to, and use addEventListener.

const clickHandler = () => {
  console.log("Hi");
};
const root = document.getElementById("root");
root.innerHTML = `<button>Click</button>`;
root.querySelector('button').addEventListener('click', clickHandler);
<div id="root"></div>

Or use a framework designed for this sort of thing.

const App = () => {
    const clickHandler = () => {
      console.log("Hi");
    };
    return <button onClick={clickHandler}>Click</button>;
};

ReactDOM.createRoot(document.querySelector('.root')).render(<App />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div class='root'></div>

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