How to Pass Values in handleChange Event in Typescript

I have noticed that most online examples of handling change events only pass in the event parameter, making the value accessible automatically. However, I encountered an error stating that the value is not found when trying to use it in my handleChange function. I am attempting to implement form validation using Formik. How can I incorporate the value in the handleChange function?

export default function MyPage() {
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [isRemoved, setIsRemoved] = useState(false);

  const [removeUser] = useMutation<Response>(USER);

  let submitForm = (email: string) => {
    User({
      variables: {
        email: email,
      },
    })
      .then(({ data }: ExecutionResult<Response>) => {
        if (data !== null && data !== undefined) {
          setIsRemoved(true);
        }
      })  };

  const formik = useFormik({
    initialValues:{ email: '' },
    onSubmit:(values, actions) => {
       setTimeout(() => {
          alert(JSON.stringify(values, null, 2));
          actions.setSubmitting(false);
          }, 1000);
        },
       validationSchema:schema
    })

    const handleChange = (e: ChangeEvent<HTMLInputElement>)=>{
      if (name!== null) && (value!==null){
      const {name,value} = event.target;
      formik.setFieldValue(name,value);
      }
     }

  return (
    <div>
              <Form
                onSubmit={e => {
                  e.preventDefault();
                  submitForm(formik.values.email);
                }}>
                <div>
                  <TextField
                    variant="outlined"
                    margin="normal"
                    id="email"
                    name="email"
                    helperText={formik.touched.email ? formik.errors.email : ''}
                    error={formik.touched.email && Boolean(formik.errors.email)}
                    label="Email"
                    value={formik.values.email}
                    //onChange={change.bind(null, 'email')}
                    onChange={handleChange}
                  />
                  <CustomButton
                    disabled={!isValid || !formik.values.email}
                    text={'Remove User'}
                  />
                </div>
              </Form>
    </div>
  );
}

When referencing this line:

const {name,value} = event.target;

I encounter the following error message despite having a conditional check using an if statement:

Property 'name' does not exist on type 'EventTarget | null'.ts(2339)

Answer №1

Make sure to first declare the values before attempting to access them. In addition, instead of using event.target, use e.target since you have declared event as follows:

 const handleChange = (e: ChangeEvent<HTMLInputElement>)

To update the code inside the handleChange() function, make the following changes:

 const { name,value } = e.target;
 if (name && value){
    formik.setFieldValue(name, value);
 }

Answer №2

When writing your handleChange function, make sure to use (event) as the parameter instead of (e), then reference event.target within the function.

handleChange= (event) => {
    const {name,value} = event.target;
    ...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When Controller Scope Goes Missing in ng-repeat

Upon glancing at my code, it should be evident that I am a newcomer to the world of Angular. I am currently developing an application that enables users to search for text, queries a database whenever the value in the text input changes, and displays a li ...

What is the method for retrieving the value of the Material-ui auto-complete component in a React.js

How can I retrieve the value of Material-UI auto-complete in react.js? I have tried productName: this.refs.productName.value productName: this.refs.productName.getValue() but neither of them seem to be working <AutoComplete hintText="Produ ...

Ways to verify the input fields across multiple tabs

Utilizing jquery validate along with jquery tabs to construct a multi-tab form. Consider a basic form : tab 1 for entering address, tab 2 for entering name, tab 3 for submission HTML <ul class="nav nav-tabs"> <li class="active"><a hr ...

An iteration in Javascript/NodeJS using the forEach loop

I am working with a forEach Loop in my code: <% users.forEach(function(user) { %> <tr> <td><%= user.studio %></td> <td><%= user.name %></td> <td><%= user.email %></td> ...

What is the best way to dynamically change the JSON-LD Script for the Schema?

Below is the script in question. Please read through it carefully. <script type="application/ld+json"> { "@context": "http://schema.org/", "@type": "Product", "name": "Bat, &q ...

Leverage arrays within a personalized filtering system

I have created an array with the structure shown below... $scope.myArr = [arg1, arg2]; Now, I am interested in developing a custom filter that will accept this array as input and compare it to another array. For instance, I intend to use it in the follow ...

Is it possible to test a Node CLI tool that is able to read from standard input with

I'm looking for a way to test and verify the different behaviors of stdin.isTTY in my Node CLI tool implementation. In my Node CLI tool, data can be passed either through the terminal or as command line arguments: cli.js #!/usr/bin/env node const ...

How can I showcase array elements using checkboxes in an Ionic framework?

Having a simple issue where I am fetching data from firebase into an array list and need to display it with checkboxes. Can you assist me in this? The 'tasks' array fetched from firebase is available, just looking to show it within checkboxes. Th ...

Issue with React modal not being visible

I'm having an issue with my code where the delete button is not triggering a modal pop-up when clicked. Although there are no compiling errors, the dev console shows the following warning: Warning:React.createElement: type is invalid--expected a stri ...

Clicking on the initial link will in turn prompt clicks on the subsequent links

Can you please provide instructions on how to correctly simulate a click on the remaining links if a click is made on the first link? jQuery('a.one_num').click(function() { jQuery('a.two_num').click(); jQuery('a.three_num&ap ...

Utilizing AJAX and PHP for seamless communication, retrieve and authenticate HTTPS SSL CERTIFICATE when interacting

Recently, I successfully created a node.js REST server located at . To develop the front-end, I am utilizing a combination of html, javascript, and php. However, when I attempted to implement an SSL certificate on the front-end, a problem arose: An issue ...

Issue with mediaelement in Angular 8: video playback does not display after 2 seconds

I'm encountering an issue with MediaElement js when trying to play videos in .m3u8 format within a slider containing multiple videos. Whenever I click on the play button for any video, only a 2-second clip is shown before the video disappears. Any as ...

Delete items within the first 10 minutes of shutting it down

Is there a way to temporarily remove a newsletter element for 10 minutes after closing it on a webpage? The idea is that once the panel is closed, it should stay hidden even if the page is refreshed within that timeframe. I was considering using local stor ...

Securing JSON-based RESTful services

I am in the process of developing a web application, where I have established a clear separation between my "frontend" server using Lighttpd to serve index.html and javascript. My frontend, powered by Backbone.js, is connected to my Node.js backend webser ...

Utilizing shared references across react-imask, react-bootstrap, and react-hook-form for a seamless integration

I have integrated react-bootstrap and react-imask using their example with IMaskMixin as shown below: import { IMaskMixin } from 'react-imask'; import { FormControl } from 'react-bootstrap'; const MaskedFormControl = IMaskMixin(({input ...

Updating JSON objects in jQuery with string keys

I have an array variable containing JSON data and I need to update specific values within the array using string keys. Here is a snippet of what my array looks like: { "all": [ { "image":{ "URL":"img/img1.jpeg", ...

"Utilizing the same generic in two interface properties in Typescript necessitates the use of the

I have created an interface as follows: interface I<T>{ foo: T arr: T[] } After defining the interface, I have implemented an identity function using it: const fn = <T>({foo, arr}: I<T>) => ({foo, arr}) When calling this function l ...

Populate an HTML table using a JavaScript array containing objects

Greetings, fellow coders! I am new to the coding world and this community, and despite my efforts in searching for a solution, I couldn't find exactly what I was looking for. So, here is my question: I have an array structured as follows: const arr ...

Is Valums Ajax file Upload capable of handling the uploaded file?

Currently, I am utilizing the Valums Ajax Fileupload script found at These are the settings I have configured: function createUploader(){ var uploader = new qq.FileUploader({ element: document.getElementById('file-uploader-de ...

Is it possible to retrieve the vertices array from a QuickHull instance in three.js?

I'm currently working on generating a geometry using QuickHull from a THREE Mesh. However, it seems that the QuickHull object only contains information pertaining to the Faces of the mesh. Does anyone know if there is a way to access the vertex infor ...