Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if my event.target is typeof HTML input element in React?

Please see this minimum example https://codepen.io/rockmandash/pen/Rzwowd

The code is this:

enter image description here

<div class="cool">
  <input type="checkbox" value="checkbox1">
  <input type="checkbox" value="checkbox2">
  <input type="checkbox" value="checkbox3">
</div>
document.querySelector(".cool").addEventListener("click", event => {
  // In React World
  // How do I check if event.target is typeof HTML.input Element?
  console.log(event.target.value);
});

I'm asking this question because I have thousands of input elements, in react, I will have to create thousands callback function.

So I move my function up to their parent, but then I have to validate if I am current clicking an input element.

Otherwise, I could potentially set the wrong event.target.value.

like image 447
Joseph Wang Avatar asked Jun 11 '19 03:06

Joseph Wang


People also ask

How can we tell what kind of element the event target is?

To check the element type pf an event target, using the is() method.

How do you pass event target value in React?

Using onChange={({ target: { value } }) => setInsertedTitle(value)} you are passing the current target value as a parameter. It is because onChange generates an Event, and you access the value by event. target.

What is the type of event target value in TypeScript?

What is the type of event in TypeScript? Events supported are: AnimationEvent , ChangeEvent , ClipboardEvent , CompositionEvent , DragEvent , FocusEvent , FormEvent , KeyboardEvent , MouseEvent , PointerEvent , TouchEvent , TransitionEvent , WheelEvent .

Is event target value always string?

target is a div which does not have value . Wrapping event. target. value || '' in String() is not necessary as it will always be either value (which is always a string or undefined ) or the empty string in the case that value is undefined .


1 Answers

if (event.target instanceof HTMLInputElement)
like image 51
programmingmusic Avatar answered Sep 21 '22 02:09

programmingmusic