useRef: como funciona esse React Hook | #AluraMais

Alura
7 Nov 202210:00

Summary

TLDRIn this video, Vinícius Neves walks through the use of the `useRef` hook in React to manipulate DOM elements directly. He demonstrates creating a form with input fields and buttons, setting references for elements like labels and inputs, and dynamically updating their properties, such as changing text and styles. Additionally, Vinícius covers how to handle form submissions and automatically focus on the input field. The video ends with a coding challenge, encouraging viewers to apply these concepts in a real-world project. It's a practical tutorial for frontend or full-stack developers exploring React's capabilities.

Takeaways

  • 😀 The video introduces the 'useRef' hook in React and explains how to use it effectively in applications.
  • 💻 The instructor starts with a new React application and demonstrates how to create a simple form with input and button elements.
  • 📝 The 'useRef' hook is used to store references to DOM elements, which can then be manipulated.
  • 🔄 The instructor shows how to manipulate the 'innerHTML' of a label using the reference stored by 'useRef', changing the label text to uppercase.
  • 🎨 DOM styling is also demonstrated by dynamically applying italic styling to the label via the 'useRef' hook.
  • 📧 An example is provided of how to create a second input field for 'email' without using references, to contrast with the earlier example.
  • 🚀 A practical use case is demonstrated where focus is returned to the input field for 'name' after the form is submitted.
  • 🎯 The instructor highlights that 'useRef' can be used to manipulate DOM elements directly, like in vanilla JavaScript, making it versatile for various tasks.
  • 🛠 A challenge is given to the viewer to manipulate the focus of input fields upon form submission, reinforcing the concepts taught.
  • 📚 The video is part of a broader React course, with links provided for further learning on frontend technologies like HTML, CSS, JavaScript, and React.

Q & A

  • What is the main topic of the video?

    -The video is about using the 'useRef' hook in React to manipulate DOM elements directly.

  • What does the presenter aim to teach in the video?

    -The presenter aims to demonstrate how to use the 'useRef' hook in React to store references to DOM elements and manipulate them, such as changing their content and styles.

  • What initial setup is done in the application?

    -The presenter creates a simple form with a label, an input field, and a save button in a newly created React application.

  • How does 'useRef' help in React?

    -'useRef' allows developers to directly interact with DOM elements by storing references to them. This is useful for accessing or modifying elements without causing re-renders.

  • What does the presenter do with the label using 'useRef'?

    -The presenter modifies the label's content using 'useRef' by setting its innerHTML to 'Nome do usuário' in uppercase.

  • How does the presenter style the label using 'useRef'?

    -The presenter changes the label's font style to italic using 'useRef' by modifying its 'style.fontStyle' property.

  • What is the purpose of 'useEffect' in the example?

    -'useEffect' is used to manipulate the DOM after the component has mounted, allowing the presenter to access and modify DOM elements using the references stored by 'useRef'.

  • How does the form submission work in the example?

    -The form has a submit handler that prevents the default action using 'event.preventDefault()' and then shifts the focus back to the name input field using 'inputRef.current.focus()'.

  • What is the challenge presented to the viewers?

    -The challenge is to create functionality where, after submitting a form, the focus is set back to the name input field using 'useRef'.

  • What is the overall goal of the video?

    -The goal of the video is to demonstrate practical use of 'useRef' in manipulating DOM elements within React applications, enhancing the viewer's understanding of this important React hook.

Outlines

00:00

👨‍💻 Introduction to UseRef Hook and Setup

In this video, Vinícius Neves introduces the topic of the `UseRef` Hook in React and its application in a new project. He begins by setting up a form with a label, an input field, and a button. He explains the purpose of referencing elements in the DOM using `UseRef` to manipulate form elements such as labels and inputs. The initial setup of the application includes creating references for both the label and input elements, and Vinícius demonstrates this by updating the label’s HTML content and styling it with `fontStyle: italic`.

05:01

✉️ Adding Email Field and Handling Form Submissions

In this section, Vinícius expands the form by adding an email field. He explains how to remove references for certain elements and updates the label from 'Name' to 'Email'. Vinícius demonstrates how to handle form submissions in React using the `onSubmit` event handler, capturing the submission event, preventing the default behavior, and processing form data. He then shows how to refocus the input field for easier multiple submissions, demonstrating the real-time manipulation of the DOM using React.

Mindmap

Keywords

💡useRef

The useRef hook is a fundamental concept in React used for accessing and interacting with DOM elements directly. In the video, the presenter demonstrates how to use useRef to store references to form elements like 'Label' and 'Input'. This hook allows manipulation of elements outside of React's normal rendering flow, such as setting focus or changing styles, as seen when the label text is modified to 'Nome do Usuário' in uppercase.

💡React

React is a JavaScript library for building user interfaces, and it is the primary framework discussed in the video. The presenter uses React to create a dynamic form, explaining concepts such as hooks and event handling to enhance interaction with the DOM. The focus is on demonstrating how React components can control the form and update elements in real-time.

💡DOM manipulation

DOM manipulation refers to the direct interaction with the Document Object Model to alter elements on a web page. In the video, the presenter illustrates DOM manipulation using useRef, showing how to dynamically update label text and apply styles such as italics. The ability to manipulate the DOM is essential for creating dynamic and interactive web applications.

💡Event handling

Event handling in React involves capturing and responding to user actions such as clicks or form submissions. In the video, the 'onSubmit' event is used to trigger a function that processes form data. After submission, the presenter demonstrates how to reset the form and refocus the input element, improving user experience by facilitating continuous form interactions.

💡useEffect

useEffect is another important React hook that allows you to perform side effects in functional components, such as data fetching or DOM updates after rendering. In the video, useEffect is utilized to update the DOM once the component is mounted, as seen when the label text is changed to 'Nome do Usuário'. This hook plays a key role in controlling when and how the application updates its interface.

💡Form submission

Form submission refers to the process of sending user input data from a form to a server or handling it within the client-side application. The presenter explains how to capture form data and handle submission in React by preventing default behavior (e.preventDefault()) and resetting the form after submission. This is demonstrated in the 'enviarFormulario' function, which processes the form and refocuses the input field.

💡State management

State management in React involves tracking and updating the state of components to reflect changes in the UI. Although not directly explained in the video, it is implicit in the presenter’s use of hooks like useRef and useEffect, which manage component behavior without directly altering the state, allowing smooth control of form inputs and dynamic updates to the interface.

💡Focus management

Focus management involves setting the focus on specific elements within a web application to improve user navigation. In the video, the presenter shows how to use the inputRef.focus() method to set the focus back to the input field after form submission, ensuring the user can immediately begin typing again. This is a key example of enhancing user experience through DOM manipulation.

💡HTML attributes

HTML attributes are used to provide additional information about HTML elements. In the video, attributes like 'type' and 'ref' are discussed, with the presenter demonstrating how to use them in React components. For example, the 'type' attribute in the input field is used to specify that it is for an email, while 'ref' is used to bind the input to a useRef hook for DOM manipulation.

💡Component lifecycle

The component lifecycle in React refers to the stages a component goes through from its creation to its removal. In the video, useEffect is tied to the component lifecycle, allowing the presenter to make DOM updates after the component is rendered. This highlights how React hooks like useEffect help developers manage component updates and interactions efficiently.

Highlights

Introduction to useRef: The video explains the purpose of the useRef hook in React, emphasizing its ability to directly manipulate the DOM.

Creating a basic form: The tutorial starts by building a simple form with a name input and a 'Save' button to demonstrate how useRef can be used.

Implementing useRef for label and input: The host shows how to create references for form elements (like label and input) and store them using the useRef hook.

DOM manipulation: Through useRef, the video demonstrates changing the inner HTML of a label element to 'USERNAME' in uppercase as a way to showcase direct DOM manipulation.

Styling with useRef: The host alters the font style of the label to italic using the reference, showcasing how styles can be modified directly on the DOM.

Adding a new field: A new email input is added, showing how form components can be extended with additional inputs and without references.

Handling form submission: The video explains how to capture form submissions and trigger specific actions using a custom `handleSubmit` function.

Setting focus programmatically: By using useRef, the video demonstrates how to automatically set the focus back to the name input after form submission.

Practical application: The video highlights scenarios where useRef can be useful, such as capturing user input for forms, focusing elements, and manipulating styles.

Best practices for useRef: Suggestions are given for when to use useRef versus other hooks like useState or useEffect for state management.

Debugging common issues: The host addresses a common mistake in fontStyle property naming, illustrating how to troubleshoot minor syntax errors.

React hook lifecycle: A quick overview of how useEffect interacts with useRef is provided, showing how changes are applied after component render.

Challenge to the viewer: The video proposes a hands-on challenge for viewers to modify the existing form and manipulate the focus using useRef.

Extending projects: Suggestions are made for integrating the useRef hook into larger React projects and enhancing form handling capabilities.

Final thoughts: The host wraps up with a discussion on the versatility of useRef and its relevance in advanced React development, encouraging developers to explore its potential.

Transcripts

play00:00

[Música]

play00:06

Olá seja muito bem vindo seja muito

play00:08

bem-vinda meu nome é Vinícius Neves eu

play00:11

vou te acompanhar nesse vídeo sobre use

play00:14

Hair que é mais um Hulk bacaninho para

play00:16

gente colocar no nosso centro de

play00:18

utilidade vamos lá

play00:20

mais uma vez eu tô aqui com uma

play00:22

aplicação recém criada não tem nada o

play00:25

que eu quero ensinar para vocês é como

play00:27

funciona e o que que a gente consegue

play00:29

fazer com ele vamos lá então vou lá para

play00:32

ver se code ou fecha tudo aqui e tenho

play00:35

aqui meu apps Já abri aqui a minha

play00:38

aplicação recém criada que eu chamei

play00:39

carinhosas certo então eu vou remover o

play00:43

reggae e eu vou criar aqui para a gente

play00:46

poder interagir um formulário e vou

play00:49

criar aqui dentro do formulário e vou

play00:51

colocar dentro dessa dívida uma chamada

play00:54

de nome vou criar logo

play00:58

e dentro dessa dívida eu vou colocar

play01:00

aqui

play01:01

um input

play01:06

e por último fora dessa dívida também eu

play01:09

vou criar um botão lá e vou chamar de

play01:11

por exemplo salvar certo e vamos ver

play01:14

aqui como você que vai ficar nua no

play01:16

navegador Voltei E tá lá nome o input e

play01:20

o botãozinho salvar legal então vamos

play01:24

aprender a utilizar esse Hulk e guardar

play01:27

essas referências como que a gente faz

play01:29

isso no react vamos lá para a gente ter

play01:32

uma referência a gente vai chamar o Hulk

play01:34

gerado

play01:40

o que que eu vou fazer eu vou guardar

play01:43

uma referência

play01:44

no constante Então vou chamar aqui de

play01:47

Label

play01:49

referência vou fazer a mesma coisa para

play01:53

o input

play01:54

Então eu tenho uma referência para lei e

play01:57

uma referência para o impulso e vou

play02:00

lançar aqui ó vou passar aqui

play02:02

então

play02:05

os ele

play02:07

imediato ele tem essa propriedade ele já

play02:09

tem esse ref Então vou chamar aqui o

play02:12

Label

play02:14

e a mesma coisa no input

play02:18

e vou passar o iogurte certo e tá aqui

play02:22

se isso não quebrou não deve ter

play02:24

alterado nada ainda lá no sul navegador

play02:27

e eu vou recarregar ele aqui ó só um

play02:30

minuto

play02:31

no console tudo funciona como deveria E

play02:35

aí o que que a gente consegue fazer Qual

play02:37

que é o poder do use raf vamos lá que eu

play02:41

vou te mostrar primeira coisa vou lançar

play02:44

aqui um e os Effect

play02:48

e aqui vou passar uma função e vou

play02:51

passar aqui como o segundo argumento uma

play02:55

rivazio se você já conhecia os reflexos

play02:58

Você sabe porque que isso serve se você

play03:00

ainda não conhece tem um vídeo que a

play03:02

gente fala especificamente desse Hulk

play03:05

para você certo então o que que a gente

play03:08

vai fazer depois que o componente tiver

play03:11

pronto né que ele foi iniciado eu vou

play03:14

vir aqui por exemplo no leborrece vou

play03:16

pegar a minha o meu corrente que é minha

play03:18

referência atual e vou manipular o

play03:21

Winner

play03:23

HTML é isso aqui que eu vou fazer eu

play03:27

quero dizer que o hino da HTML dessa

play03:29

leibo vai passar a ser nome do usuário

play03:33

tudo maiúsculo para a gente ver que tem

play03:35

alguma diferença o nome do usuário Vou

play03:39

salvar e vamos lá para o navegador Vou

play03:42

recarregar a página ó repara tá aqui ó a

play03:46

coisa acontece tão rápido aqui não dá

play03:48

nem para ver né mas tá aqui a nossa Opa

play03:51

Deixa eu voltar aqui a nossa manipulação

play03:54

do Dom tá funcionando o que mais que a

play03:56

gente consegue fazer a gente pode vir

play03:57

aqui por exemplo

play03:59

no

play04:01

leborreffe.corrente ponto

play04:03

está E se eu não me engano Style e sei

play04:07

lá vamos colocar aqui um fonte

play04:09

Style por exemplo a gente consegue fazer

play04:12

um Itálico vamos ver se minha memória tá

play04:14

boa o suficiente e aí eu quero dizer que

play04:16

o estilo na minha líder vai ter um fonte

play04:19

Style

play04:20

Itálico vamos ver se isso aqui vai

play04:22

funcionar voltando no navegador

play04:24

recarreguei

play04:29

aqui um erro do console aqui grandão

play04:31

aqui dizendo Olha só você tá tentando

play04:33

fazer fonte de tarde é porque aqui é não

play04:36

está

play04:37

no singular vai carregar a página agora

play04:41

sim ó tá lá em Itália

play04:45

a nossa ponte então isso daqui é o que a

play04:48

gente consegue fazer

play04:49

por exemplo então a gente consegue ir lá

play04:52

no Dom e manipular esse cara legal então

play04:56

vamos fazer o seguinte eu vou adicionar

play04:58

aqui um cliente

play05:00

eu vou chamar aqui de

play05:03

seu nome

play05:06

e vou também colocar aqui mais uma lei

play05:09

vou copiar tudo só que eu não quero mais

play05:12

passar essas referências vou deixar sem

play05:15

referência nenhuma

play05:17

vou tirar aqui a referência

play05:20

e agora não vai ser nome vai ser e-mail

play05:22

E aí eu vou colocar aqui e meio certo a

play05:27

gente podia colocar aqui no type

play05:30

e vamos chamar aqui em e-mail certo e

play05:35

agora recarregando a página toda confusa

play05:37

muito grande Tá lá a gente tem o nome e

play05:38

tem o e-mail E aí uma das coisas que a

play05:42

gente pode fazer também é dado que eu

play05:44

uso formulário por exemplo metido a

play05:46

gente pode capturar isso e dar o foco

play05:49

por exemplo para o usuário conseguir

play05:52

fazer várias adições em sequência E aí

play05:55

como é que a gente faria isso vamos lá

play05:56

primeira coisa bom capturar um sub

play06:00

limite

play06:03

E aí vamos colocar aqui vou chamar uma

play06:05

função chamada de enviar formulário

play06:08

formulário percebe perguntando da onde

play06:10

esse cara vem vai vir agora vamos criar

play06:13

conste formular enviar formulário para

play06:16

receber o maior

play06:19

e a gente vai ter acesso ao evento

play06:23

aí a gente vai fazer um evento ponto

play06:25

Private 20

play06:28

[Música]

play06:30

E aí o que eu quero fazer depois que eu

play06:33

formulário possível aqui a gente pode

play06:34

enviar

play06:36

os dados para algum lugar pode ser por

play06:39

uma pi pode ser por um desperte de uma

play06:41

ação pode ser para um nível existente

play06:45

pode fazer qualquer coisa aqui com que

play06:47

foi enviado e depois cuidado foi enviado

play06:49

a gente pode por exemplo vir no

play06:55

inputing.focus ou seja o curso vai

play06:59

voltar para o nosso input de nome certo

play07:03

vamos testar aqui visse isso aqui

play07:06

funcionava Vou salvar aqui e vamos para

play07:10

página Vou recarregar para ter certeza ó

play07:12

o foco tá no nome vou dar um Tab e o

play07:16

foco tá no e-mail você mandar salvar

play07:18

repara o formulário é submetido e o foco

play07:21

volta lá para o input nome Então esse é

play07:25

o poder do é para isso que ele foi

play07:29

desenvolvido a gente tem acesso de fato

play07:31

ao Dom ao elemento do Dom e pode

play07:34

manipular ele como se Faria react ou

play07:37

seja direto usando api do Dom ok a gente

play07:41

pode fazer HTML pode fazer clés list

play07:44

pode mexer enfim fica aí de acordo com a

play07:47

sua necessidade ou as possibilidades são

play07:50

infinitas legal E aí para não deixar

play07:54

aqui só esse conceito um pouco abstrato

play07:57

eu vou trazer um desafio para você de

play07:59

novo no organo a gente tem já o firma

play08:02

dele aqui e qual que é o desafio que eu

play08:05

vou trazer para você a gente desenvolver

play08:08

esse projeto no curso da aluna de reax

play08:12

com JavaScript

play08:14

gente criou toda essa aplicação do zero

play08:16

chegou não tinha nada levou toda ela lá

play08:18

e a gente já passou por algum desafio

play08:20

por alguns desafios e o que eu vou

play08:23

trazer para você é quando formulário do

play08:26

organo foi submetido você vai lá e vai

play08:30

manipular o projeto vai manipular o dom

play08:32

vou guardar uma referência para o nome e

play08:34

vai definir de forma o foco nesse input

play08:37

de nome Essa é o que eu tenho para você

play08:40

e para trazer para você de desafio Ok

play08:43

então vai lá pega o formulário que já

play08:46

foi desenvolvido já tem um método lá já

play08:48

tem uma rotina lá você vai poder fazer

play08:50

vai poder sentar o foco no input quando

play08:55

formulário for preenchido legal então

play08:58

era isso que eu tinha para trazer para

play09:00

vocês o link do organo do Projeto vai

play09:03

estar disponível aqui para você fica

play09:04

tranquilo e eu espero que você tenha

play09:06

gostado do rap e agora quando você

play09:09

precisar acessar algum elemento você já

play09:12

sabe que é esse para você ajudar então

play09:15

Guarda aí no seu centro de utilidade

play09:16

porque ele muito provavelmente vai ser

play09:19

útil Em algum momento da sua jornada de

play09:21

pessoas desenvolvedora front-end ou full

play09:24

steck ou mesmo back end que está se

play09:26

aventurando aqui no frontins certo então

play09:28

é isso que o dia para mostrar para vocês

play09:29

uma vida longa e Próspera e eu te vejo

play09:32

no próximo

play09:33

na lura você pode aprender a fazer site

play09:36

webs com HTML CSS java script temos

play09:39

também cursos de ferramentas de

play09:40

frameworks importantes como react

play09:46

[Música]

Rate This

5.0 / 5 (0 votes)

関連タグ
React hooksuseRefDOM manipulationJavaScript tutorialWeb developmentForm handlingFrontendProgrammingHTML formsFullstack
英語で要約が必要ですか?