What is the reason behind FieldSelect returning a string instead of an object like FieldCheckbox?

FieldSelect component from Sharetribe documents is giving me a string, while FieldCheckbox is returning a JSON object.

In a specific scenario, I want FieldSelect to store a JSON object. How can I achieve this?

Below is the code snippet for reference:

I'm new to REACT and would greatly appreciate if someone could explain why this behavior is occurring.

Code Implementation

<FieldSelect
  name={subGroupCategoryKey}
  id={subGroupCategoryKey}
  label={categoryLabel}
>
  {relevantSubGroupCategoryOptions.map(c => (
    <option key={c.key} value={c.key}>
      {c.label}
    </option>
  ))}
</FieldSelect>

FieldSelect

import React from 'react';
import PropTypes from 'prop-types';
import { Field } from 'react-final-form';
import classNames from 'classnames';
import { ValidationError } from '../../components';

import css from './FieldSelect.module.css';

const FieldSelectComponent = props => {
  const { rootClassName, className, id, label, input, meta, children, ...rest } = props;

  if (label && !id) {
    throw new Error('id required when a label is given');
  }

  const { valid, invalid, touched, error } = meta;

  // Display error message and input styles only if field has been touched and validation failed.
  const hasError = touched && invalid && error;

  const selectClasses = classNames(css.select, {
    [css.selectSuccess]: valid,
    [css.selectError]: hasError,
  });
  const selectProps = { className: selectClasses, id, ...input, ...rest };

  const classes = classNames(rootClassName || css.root, className);
  return (
    <div className={classes}>
      {label ? <label htmlFor={id}>{label}</label> : null}
      <select {...selectProps}>{children}</select>
      <ValidationError fieldMeta={meta} />
    </div>
  );
};

// Default props and prop types definition
...

const FieldSelect = props => {
  return <Field component={FieldSelectComponent} {...props} />;
};

export default FieldSelect;

FieldCheckbox

import React from 'react';
import { node, string } from 'prop-types';
import classNames from 'classnames';
import { Field } from 'react-final-form';

import css from './FieldCheckbox.module.css';

const IconCheckbox = props => {
  const { className, checkedClassName, boxClassName } = props;
  return (
    <SVG >
    </svg>
  );
};

// Default props and prop types definition
...

const FieldCheckboxComponent = props => {
  const {
    rootClassName,
    className,
    svgClassName,
    textClassName,
    id,
    label,
    useSuccessColor,
    onChange: handleChange,
    ...rest
  } = props;

  const classes = classNames(rootClassName || css.root, className);

  const handleOnChange = (input, event) => {
    const { onBlur, onChange } = input;
    onChange(event);
    onBlur(event);
    handleChange && handleChange(event);
  };

  // Rendering checkbox with label
  ...

  return (
    <span className={classes}>
      ...
  );

};

// Default props and prop types definition
...

export default FieldCheckboxComponent;

Answer №1

When a user submits a form, the name of the input serves as the key and the user's input is the value.

FieldSelect acts as a Final Form wrapper for the HTML

<select name="someName">
element, allowing only one value to be selected at a time. Therefore, the submission will include something like
someName: 'valueOfSelectedOption'
.

FieldCheckbox is designed as a wrapper for the HTML <checkbox> element. The Final Form library employs an "array" setup for checkboxes with the same name.

For instance, if your form includes

<checkbox name="asdf" value="a"/><checkbox name="asdf" value="b"/>
, and the user selects both checkboxes, the submitted value would appear as follows:
asdf: ["a", "b"]
.

Note: If Final Form library is not used, the default HTML submit output would have been asdf=a&asdf=b.

Therefore, FieldCheckbox utilizes an array as its output format instead of JSON (even though they may appear similar in this case).

Below are some helpful links related to React Final Form that you may find useful:

If you wish to modify the field's default value, you should refer to the parse (and format) field props:

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

Why won't JavaScript functions within the same file recognize each other?

So I have multiple functions defined in scriptA.js: exports.performAction = async (a, b, c) => { return Promise.all(a.map(item => performAnotherAction(item, b, c) ) ) } exports.performAnotherAction = async (item, b, c) => { console.log(`$ ...

Sending a parameter to the window.onload callback function

Is there a way to pass parameters from ModelAndView to a window.onload function in JavaScript within an HTML file? Here is an example of how it can be done: @RequestMapping(value = "/admin/printtext") public ModelAndView printtext() { ModelAndView mo ...

Struggling with making react-hook-form correctly validate an email address

I've been struggling for a long time to make this validation work correctly, but it seems impossible. I even added some text at the bottom to display an error message related to the email, but it always shows no error, regardless of the situation. Ed ...

Optimal method for personalizing MUI 5 Drawer while avoiding CSS conflicts

Currently, I am exploring how to personalize MUI 5 components by leveraging theming and props more and minimizing the use of CSS overrides (which can negate the benefits of MUI). To start off, I have created my own theme: export const theme = createTheme( ...

Toggle between different socket.io servers for seamless connectivity

I'm looking for help with a situation where I need a socket.io client to connect to server A, disconnect, and then connect to server B. Any ideas on how I can achieve this? Thanks in advance! UPDATE: Attached below is the code snippet that's gi ...

Contrasting ./ and $ in React project module imports

The creator of this particular project has utilized a different path to import a component: import { client } from '$lib/graphql-client' I'm curious: What is the significance of the $ symbol in this case? How does it differ from something ...

Encountered an error in Pytorch LSTM conversion to ONNX.js: "Uncaught (in promise) Error: LSTM_4 node does not recognize input ''

I am attempting to execute a Pytorch LSTM network in the browser, but I am encountering the following error: graph.ts:313 Uncaught (in promise) Error: unrecognized input '' for node: LSTM_4 at t.buildGraph (graph.ts:313) at new t (graph.t ...

SVGs do not display on iPhones

Having some issues with my code - specifically, I have an SVG animation that seems to work on all devices except iPhones. I've been struggling to find a solution. Here is the code snippet for the SVG: <div class="contenuto-svg"> <svg vi ...

Methods for invoking a function from a separate .js file within React Native Expo

I'm new to using React and I've come across a challenge: In my Main.js file, there is a button: import * as React from 'react'; import { StyleSheet, Text, View, SafeAreaView, Pressable, Alert } from 'react-native'; import { M ...

What is the method to include a CoffeeScript file in my project?

Currently, I am attempting to follow the steps outlined in this CoffeScript tutorial. After opening the terminal and navigating to the directory where simpleMath.coffee is located, I proceeded to run node and entered var SimpleMath = require('./simpl ...

How can the outer function be connected to the resolve method of $routeProvider?

Here is a functional code snippet: $routeProvider.when('/clients', { templateUrl:'/views/clients.html', controller:'clientsController', resolve: { rights: function ( ...

Issues with Disabling the Browser's Back Button with jquery

I have been attempting to prevent the back button from functioning in a specific Browser, Microsoft Bing. Interestingly, my code works only if I click somewhere in the window first. If I don't click anywhere and try to go back directly, it still allow ...

Error: Attempting to access a property of an undefined value, please verify the key name is

Attempting to incorporate dynamic elements into the assignment, I have written the following code: var contentList = Object.keys(content)[0]; $scope.model.currentLoadedContent[contentList] = content[Object.keys(content)[0]] When trying to execute the seco ...

Retrieving a universal variable within AngularJS

Is there a way to initialize an Angular model using a JSON object that is embedded within an HTML page? Take this as an example: <html> <body> <script type="text/javascript" charset="utf-8"> var tags = [{&q ...

Error message: `Socket.io-client - Invalid TypeError: Expected a function for socket_io_client_1.default`

I have successfully installed socket.io-client in my Angular 5.2 application, but after trying to connect (which has worked flawlessly in the past), I am encountering a strange error. TypeError: socket_io_client_1.default is not a function at new Auth ...

The React useEffect feature seems to be updating just one value

I am struggling to find a solution to this issue, even though I believe there is likely a simple explanation. I have two API calls, getNarrativeReferences and getNarrativeHeaders, that return values for two separate arrays in searchState. However, upon pag ...

Stopping the page from scrolling back to the top when an asynchronous update occurs in Angular

Once the asynchronous request is complete, I dynamically add a new element to the top with this code snippet: Array.prototype.unshift.apply(scope.conversation, conversation.data.message); The issue arises when the added element causes the scroll position ...

Exploring the functionalities of class methods within an Angular export function

Is it possible to utilize a method from an exported function defined in a class file? export function MSALInstanceFactory(): IPublicClientApplication { return new PublicClientApplication({ auth: AzureService.getConfiguration(), <-------- Com ...

Identify if a process operates synchronously or asynchronously

Can you identify in node.js, with the help of a function, if a method is synchronous or asynchronous? I am interested in creating a function that achieves the following: function isSynchronous(methodName) { //check if the method is synchronous, then ...

Interactive data table feature in React, transferring selected row data to a modal pop-up

I am currently developing an offline Progressive Web App (PWA) using ReactJS and have integrated the react-data-table-component, which has been very helpful so far. Within the table, I have implemented an onRowClicked function that triggers whenever a row ...