Question from Student: Can a single function be created to manage all text fields, regardless of the number of fields present?

In my SPFX project using React, TypeScript, and Office UI Fabric, I've noticed that I'm creating separate functions for each text field in a form. Is there a way to create a single function that can handle multiple similar fields, but still maintain unique states for each?

For example, here is one text field function:

private _onReason = (ev: React.FormEvent<HTMLInputElement>, newValue?: string) => {
    this.setState({
      Reason: newValue
    });
  }

And here is another almost identical one:

private _onPurpose = (ev: React.FormEvent<HTMLInputElement>, newValue?: string) => {
    this.setState({
      Purpose: newValue
    });
  }

I want users to be able to submit the states of these multiple text fields with more concise code.

I came across this resource but I'm not sure how to integrate it into my project:

The issue I encountered when trying to implement the solution from Pluralsight is related to using MS fabric UI and the

React.FormEvent<HTMLInputElement>, NewValue?: string)
format in the handler function I attempted below:

public handleChange (evt: React.FormEvent<HTMLInputElement>, newValue?: string) {
    const value = evt.target.value;
    this.setState({
      ...this.state,
      [evt.target.name]: value
    });
  }

The error occurs at const value and [evt.target.name], specifically.

UPDATE: I tried implementing something suggested in Peter's link, which helped resolve one error (the value error), but I'm still facing issues with [evt.target.name] (specifically, the 'name' portion).

Answer №1

Your question is clear and concise, and I appreciate the link you shared for additional context. In my experience with React hooks, I've found that using an anonymous function in the JSX attribute can help reduce code verbosity. Here's an example:

<label>
  First name
  <input
    type="text"
    onChange={(e) => {setFirstName(e.target.value)}}
  />
</label>
<p> {firstName} </p>

Keep in mind that if you're not familiar with TypeScript, you'll need to specify types for the event (e) and the firstName variable. If you're not using React hooks, you may have to destructure your state object and handle more syntax due to a larger state with multiple objects. I hope this information proves helpful to you!

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

Avoid unwanted typeof warnings in TypeScript and WebStorm combination

How can I handle unwanted TypeScript checks related to JavaScript usage in today's development environment? Consider the following function: function connect(config: string): void { // Getting warning for the line that follows: // typeof ...

Avoid refreshing the page upon pressing the back button in AngularJS

Currently, I am working on building a web application that heavily relies on AJAX with AngularJS. One issue I am facing is that when the user clicks the back button on their browser, the requests are being re-made which results in data having to be reloa ...

The Google Charts chartRangeFilter displays incorrectly upon reducing the height to a specific, seemingly random level

I am relatively new to web coding and currently working on a dashboard project for my client. I am using Google Charts to display the water level data that I collect. My issue is with the chartRangeFilter control - it works fine when the height is large en ...

Calculate the total amount from the selected items on the list, depending on the clicked ('active') element

My main objective is to achieve the following: Before any clicks || After the user selects the desired item After conducting some research, I successfully implemented this using vue.js https://jsfiddle.net/Hanstopz/Lcnxtg51/10/ However, I encountered ...

Having difficulties accessing the /playlists route with express and app.get in my code

I am encountering a 404 status code error when trying to access app.get('/playlists'). The browser displays "cannot GET /playlists" and I can't seem to figure out why. Here is the code I am using: var express = require('express&apos ...

Is jQuery still recommended for adding animations in VueJS?

In my component's methods object, I currently have the following code snippet: startImageAnimation() { $('.splash-image').fadeIn(1400, () => { setTimeout(function() { $('.splash-image').fadeOut(1400, () ...

Having trouble with the functionality of Bootstrap's nav-tabs 'show' feature?

I'm having some issues with adding a search box to my glossary. The glossary is created using nested unordered lists (ul) within another ul that has classes of "nav-tabs" and "bootstrap". In the JavaScript code, I am using the following snippet: $j(& ...

Calculate the total of all values associated with a dynamically generated key within an array of objects

I'm trying to calculate the sum of similar keys in an array of objects. Each object in the array will have some common keys, but not all arrays will share the same set of keys. I'm considering storing these keys in a separate array and then loopi ...

Is it possible to transform an arrow function into a regular function?

Currently, I am working my way through the AJAX type ahead course in Javascript 30 by Wes Bos. As I progress through this course, I have made a conscious effort to minimize my use of ES6 features for the sake of honing my skills. If you want to see the fi ...

Show the button's value in the textbox and update the selected button's color using JavaScript

I am having difficulty changing the background color of a selected button after displaying its value in a textbox. The code below successfully displays the button value in the textbox, but I can't figure out how to change the background color of the s ...

What is the best way to dynamically adjust the select option?

I need help with handling JSON objects: [ { id: "IYQss7JM8LS4lXHV6twn", address: "US", orderStatus: "On the way", }, ]; My goal is to create a select option for the order status. If the current status is "On ...

Retrieve the maximum numerical value from an object

My goal is to obtain the highest value from the scores object. I have a global object called "implementations": [ { "id": 5, "project": 'name project', "scores": [ { "id": 7, "user_id": 30, "implement ...

Expand and collapse dynamically while scrolling

// Closing Button for Main Navigation $('button#collapse-button').click(function () { $('nav#main-nav').toggleClass('closed'); }); $(window).on('scroll', function () { if ($(wind ...

Tips for maintaining the chat scroll position while typing on mobile devices

Check out this example page: https://codesandbox.io/s/summer-flower-uxw47?file=/index.html:4175-4223 The issue at hand is that when accessing the site from a mobile device and tapping on the input field, the keyboard pops up. This causes the text in the m ...

Creating a custom component in Angular 2 that includes several input fields is a valuable skill to have

I have successfully created a custom component in Angular 2 by implementing the CustomValueAccessor interface. This component, such as the Postcode component, consists of just one input field. <postcode label="Post Code" cssClass="form-control" formCon ...

Leveraging regular expressions for image domains within NextJS next.config.js

Is it possible to use regex in next.config.js to allow image domains? Giphy uses different numbers for its endpoints (e.g. media0.giphy.com, media2.giphy.com), but my regex isn't working and I'm seeing this error message: hostname "media0.gi ...

Dealing with cross-origin error issues when using json.parse in React / MERN development

My data structure functions correctly when I use console.log: console.log(JSON.parse([values.category2]).needed_skills); However, when I pass the output of JSON.parse([values.category2]).needed_skills to a component in my application, the entire system c ...

Tips for testing an Angular 6 service with a dependency that utilizes private methods and properties to alter the output of public methods and properties

I've encountered a challenge while attempting to write a Jasmine/Karma test for an Angular 6 app. The test is for a service in my application that relies on another service with private properties and methods, causing my tests to consistently fail. W ...

Guide on creating 2 select inputs with distinct elements?

Imagine you have two select inputs called 'Favorite Fruits' and 'Least Favorite Fruits'. Both of them contain a list of 5 fruits. // The following code is an example to demonstrate the issue <select name='favoriteFruits'& ...

Turning JSON data into an array format, omitting the keys

Can someone help me with a query that will retrieve a specific column from the database and return it in this format: [ { "tenantName": "H&M" }, { "tenantName": "McDonalds" } ] I would like to transform ...