# Eventos

Ao contrário do JavaScript puro, no React podemos invocar funções diretamente ao lidarmos com eventos. Neste exemplo, vamos mostrar a idade de uma pessoa quando clicamos no seu nome.

Embora seja possível usar a função do JavaScript puro diretamente no componente, essa abordagem não é a mais recomendada. Vamos explorar uma solução que envolve chamar uma função separada, o que ajuda a modularizar o código de forma mais eficiente.

```jsx
import React from 'react';

interface BoasVindasProps {
    nome: string;
    idade: number;
}

function BoasVindas(props: BoasVindasProps) {
    function handleClick() {
        alert("Idade: " + props.idade);
    }

    return (
        <div onClick={handleClick}>
            <h1>Olá, seja bem-vindo {props.nome}</h1>
        </div>
    )
}

export default BoasVindas
```

Outra possibilidade é passar a função por parâmetro, executando ela no componente pai (que nesse caso é App). Para isso, devemos definir a função do evento no componente pai, passar a função como prop ao filho e, no filho, utilizar a função através da props, da seguinte forma.

Em App.tsx:

```jsx
import React from 'react';
import './App.css';

// Importa o componente que criamos de seu diretório
import BoasVindas from './components/BoasVindas/BoasVindas';

function App() {
  function handleClick(idade: number) {
    alert("Idade: " + idade);
  }

  return (
    <div>
      <BoasVindas nome="Fulano" idade={23} onClick={handleClick} />
      <BoasVindas nome="Ciclano" idade={14} onClick={handleClick} />
    </div>
  );
}

export default App;
```

No Componente:

```jsx
import React from 'react';

interface BoasVindasProps {
    nome: string;
    idade: number;
    onClick: (idade: number) => void;
}

function BoasVindas(props: BoasVindasProps) {
    return (
        <div onClick={() => { props.onClick(props.idade) }}>
            <h1>Olá, seja bem-vindo {props.nome}</h1>
        </div>
    )
}

export default BoasVindas
```

Resultado:

<figure><img src="/files/j0Li3MB6qEhhURV2v6um" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://uclsanca.gitbook.io/learn/web-avancado/reactjs/eventos.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
