useRef: como funciona esse React Hook | #AluraMais
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
👨💻 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`.
✉️ 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
💡React
💡DOM manipulation
💡Event handling
💡useEffect
💡Form submission
💡State management
💡Focus management
💡HTML attributes
💡Component lifecycle
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
[Música]
Olá seja muito bem vindo seja muito
bem-vinda meu nome é Vinícius Neves eu
vou te acompanhar nesse vídeo sobre use
Hair que é mais um Hulk bacaninho para
gente colocar no nosso centro de
utilidade vamos lá
mais uma vez eu tô aqui com uma
aplicação recém criada não tem nada o
que eu quero ensinar para vocês é como
funciona e o que que a gente consegue
fazer com ele vamos lá então vou lá para
ver se code ou fecha tudo aqui e tenho
aqui meu apps Já abri aqui a minha
aplicação recém criada que eu chamei
carinhosas certo então eu vou remover o
reggae e eu vou criar aqui para a gente
poder interagir um formulário e vou
criar aqui dentro do formulário e vou
colocar dentro dessa dívida uma chamada
de nome vou criar logo
e dentro dessa dívida eu vou colocar
aqui
um input
e por último fora dessa dívida também eu
vou criar um botão lá e vou chamar de
por exemplo salvar certo e vamos ver
aqui como você que vai ficar nua no
navegador Voltei E tá lá nome o input e
o botãozinho salvar legal então vamos
aprender a utilizar esse Hulk e guardar
essas referências como que a gente faz
isso no react vamos lá para a gente ter
uma referência a gente vai chamar o Hulk
gerado
o que que eu vou fazer eu vou guardar
uma referência
no constante Então vou chamar aqui de
Label
referência vou fazer a mesma coisa para
o input
Então eu tenho uma referência para lei e
uma referência para o impulso e vou
lançar aqui ó vou passar aqui
então
os ele
imediato ele tem essa propriedade ele já
tem esse ref Então vou chamar aqui o
Label
e a mesma coisa no input
e vou passar o iogurte certo e tá aqui
se isso não quebrou não deve ter
alterado nada ainda lá no sul navegador
e eu vou recarregar ele aqui ó só um
minuto
no console tudo funciona como deveria E
aí o que que a gente consegue fazer Qual
que é o poder do use raf vamos lá que eu
vou te mostrar primeira coisa vou lançar
aqui um e os Effect
e aqui vou passar uma função e vou
passar aqui como o segundo argumento uma
rivazio se você já conhecia os reflexos
Você sabe porque que isso serve se você
ainda não conhece tem um vídeo que a
gente fala especificamente desse Hulk
para você certo então o que que a gente
vai fazer depois que o componente tiver
pronto né que ele foi iniciado eu vou
vir aqui por exemplo no leborrece vou
pegar a minha o meu corrente que é minha
referência atual e vou manipular o
Winner
HTML é isso aqui que eu vou fazer eu
quero dizer que o hino da HTML dessa
leibo vai passar a ser nome do usuário
tudo maiúsculo para a gente ver que tem
alguma diferença o nome do usuário Vou
salvar e vamos lá para o navegador Vou
recarregar a página ó repara tá aqui ó a
coisa acontece tão rápido aqui não dá
nem para ver né mas tá aqui a nossa Opa
Deixa eu voltar aqui a nossa manipulação
do Dom tá funcionando o que mais que a
gente consegue fazer a gente pode vir
aqui por exemplo
no
leborreffe.corrente ponto
está E se eu não me engano Style e sei
lá vamos colocar aqui um fonte
Style por exemplo a gente consegue fazer
um Itálico vamos ver se minha memória tá
boa o suficiente e aí eu quero dizer que
o estilo na minha líder vai ter um fonte
Style
Itálico vamos ver se isso aqui vai
funcionar voltando no navegador
recarreguei
aqui um erro do console aqui grandão
aqui dizendo Olha só você tá tentando
fazer fonte de tarde é porque aqui é não
está
no singular vai carregar a página agora
sim ó tá lá em Itália
a nossa ponte então isso daqui é o que a
gente consegue fazer
por exemplo então a gente consegue ir lá
no Dom e manipular esse cara legal então
vamos fazer o seguinte eu vou adicionar
aqui um cliente
eu vou chamar aqui de
seu nome
e vou também colocar aqui mais uma lei
vou copiar tudo só que eu não quero mais
passar essas referências vou deixar sem
referência nenhuma
vou tirar aqui a referência
e agora não vai ser nome vai ser e-mail
E aí eu vou colocar aqui e meio certo a
gente podia colocar aqui no type
e vamos chamar aqui em e-mail certo e
agora recarregando a página toda confusa
muito grande Tá lá a gente tem o nome e
tem o e-mail E aí uma das coisas que a
gente pode fazer também é dado que eu
uso formulário por exemplo metido a
gente pode capturar isso e dar o foco
por exemplo para o usuário conseguir
fazer várias adições em sequência E aí
como é que a gente faria isso vamos lá
primeira coisa bom capturar um sub
limite
E aí vamos colocar aqui vou chamar uma
função chamada de enviar formulário
formulário percebe perguntando da onde
esse cara vem vai vir agora vamos criar
conste formular enviar formulário para
receber o maior
e a gente vai ter acesso ao evento
aí a gente vai fazer um evento ponto
Private 20
[Música]
E aí o que eu quero fazer depois que eu
formulário possível aqui a gente pode
enviar
os dados para algum lugar pode ser por
uma pi pode ser por um desperte de uma
ação pode ser para um nível existente
pode fazer qualquer coisa aqui com que
foi enviado e depois cuidado foi enviado
a gente pode por exemplo vir no
inputing.focus ou seja o curso vai
voltar para o nosso input de nome certo
vamos testar aqui visse isso aqui
funcionava Vou salvar aqui e vamos para
página Vou recarregar para ter certeza ó
o foco tá no nome vou dar um Tab e o
foco tá no e-mail você mandar salvar
repara o formulário é submetido e o foco
volta lá para o input nome Então esse é
o poder do é para isso que ele foi
desenvolvido a gente tem acesso de fato
ao Dom ao elemento do Dom e pode
manipular ele como se Faria react ou
seja direto usando api do Dom ok a gente
pode fazer HTML pode fazer clés list
pode mexer enfim fica aí de acordo com a
sua necessidade ou as possibilidades são
infinitas legal E aí para não deixar
aqui só esse conceito um pouco abstrato
eu vou trazer um desafio para você de
novo no organo a gente tem já o firma
dele aqui e qual que é o desafio que eu
vou trazer para você a gente desenvolver
esse projeto no curso da aluna de reax
com JavaScript
gente criou toda essa aplicação do zero
chegou não tinha nada levou toda ela lá
e a gente já passou por algum desafio
por alguns desafios e o que eu vou
trazer para você é quando formulário do
organo foi submetido você vai lá e vai
manipular o projeto vai manipular o dom
vou guardar uma referência para o nome e
vai definir de forma o foco nesse input
de nome Essa é o que eu tenho para você
e para trazer para você de desafio Ok
então vai lá pega o formulário que já
foi desenvolvido já tem um método lá já
tem uma rotina lá você vai poder fazer
vai poder sentar o foco no input quando
formulário for preenchido legal então
era isso que eu tinha para trazer para
vocês o link do organo do Projeto vai
estar disponível aqui para você fica
tranquilo e eu espero que você tenha
gostado do rap e agora quando você
precisar acessar algum elemento você já
sabe que é esse para você ajudar então
Guarda aí no seu centro de utilidade
porque ele muito provavelmente vai ser
útil Em algum momento da sua jornada de
pessoas desenvolvedora front-end ou full
steck ou mesmo back end que está se
aventurando aqui no frontins certo então
é isso que o dia para mostrar para vocês
uma vida longa e Próspera e eu te vejo
no próximo
na lura você pode aprender a fazer site
webs com HTML CSS java script temos
também cursos de ferramentas de
frameworks importantes como react
[Música]
Weitere ähnliche Videos ansehen
Create Your First C# Windows Forms Application using Visual Studio
useRef Hook | Mastering React: An In-Depth Zero to Hero Video Series
Learn HTML Forms In 25 Minutes
Firebase phone authentication | Sign in | Phone country code | React phone input | Reactjs,firebase
HTML - Forms - W3Schools.com
HTML Forms and Inputs | HTML5 Tutorial for Beginners
5.0 / 5 (0 votes)