DEV Community

miguelf1671
miguelf1671

Posted on

event.target in React

In React, using event.target is essential and will be used a lot through out your project. Event.target is used to access a DOM Element, for example this is done when a user clicks a button and when its clicked event.target would be the reference to that button element. You can also think of it as a detective that its job is to identify what element the user has taken action with. Once the detective knows what element the user has triggered it then can also get you information of what has changed in that element. For example if you have a text input, event.target will refer to the input field when the user starts typing text, but before you can see that information you need to call a event handler like onChange. So it can look something like this:

<input type="text" onChange={handleInputChange} />

You can either write all your code inside onChange but it is usually neater if you make a separate function to handle the onChange, especially if you plan to use it multiple times. Here is what the handleInputChange function would look like:

function handleInputChange(event) {
const input = event.target;
const text = input.value;
console.log("You typed:", text);
}

Here you can see that event.target is the input field and you can then access the text that the user has typed by getting the value. So we pass down the variable input and get the value with .value. The const variable text is the same as event.target.value, that's why we can then return text as the value of the input change. Understanding this crucial into making sure your app reacts the way you want it to.

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay