Is it possible to change the value of a react-final-form Field component using the onSelect function?

I am currently working on a React application using TypeScript and incorporating the Google Places and Geocoder APIs through various React libraries such as "react-places-autocomplete": "^7.2.1" and "react-final-form": "^6.3.0".

The issue I'm facing revolves around updating the value in the react-final-form field after the user selects a suggestion from the auto-complete feature. Below is a snippet of the code showcasing the onSelect functions:

onSelect Functions:

const handleCitySelect = (selectedCity: string) => {
    geocodeByAddress(selectedCity)
      .then(results => getLatLng(results[0]))
      .then(latlng => {
        setCityLatLng(latlng);
      }); <-- Here I need to update the field with selectedCity
  };

  const handleVenueSelect = (selectedVenue: string) => {
    geocodeByAddress(selectedVenue)
      .then(results => getLatLng(results[0]))
      .then(latlng => {
        setVenueLatLng(latlng);
      }); <-- Here I need to update the field with selectedVenue
  };

React final form:

      <FinalForm <-- react-final-form component

        validate={validate}
        initialValues={activity}
        onSubmit={handleFinalFormSubmit}
        render={({ handleSubmit, invalid, pristine }) => (
          <Form onSubmit={handleSubmit} loading={loading}> <-- semantic-ui-react component
            <Field
              name="title"
              placeholder="Title"
              value={activity.title}
              component={TextInput}
            />
            <Field
              name="description"
              placeholder="Description"
              rows={3}
              value={activity.description}
              component={TextAreaInput}
            />
            // Other fields...

            <Field <-- field I need to update after the onSelect callback
              component={PlaceInput}
              name="city"
              placeholder="City"
              options={{ types: ["(cities)"] }}
              value={activity.city}
              onSelect={handleCitySelect}
            />
            <Field <-- field I need to update after the onSelect callback
              component={PlaceInput}
              name="venue"
              placeholder="Venue"
              options={{
                location: new google.maps.LatLng(cityLatLng),
                radius: 1000,
                types: ["establishment"]
              }}
              value={activity.venue}
              onSelect={handleVenueSelect}
            />
<...>

The PlaceInput component acts as a custom wrapper for the PlacesAutocomplete component that provides suggestions based on user input.

If anyone has a solution or suggestions for this issue, I would greatly appreciate it. I've searched online extensively but couldn't find a straightforward resolution. Feel free to ask for more information or code snippets if needed.

Thank you,

Answer №1

In order to set the field value, your PlaceInput must use input.onChange(newValue).

Additionally, refrain from passing a value prop to Field. This is only applicable for checkboxes and radio buttons.

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

Tips for Elevating State with React Router Version 6

Looking for advice on sharing state between two routes in my project. I'm debating whether to lift state up from my AddContact component to either the Layout or App components in order to share it with the ContactList. The Layout component simply disp ...

Building a Next.js application that supports both Javascript and Typescript

I currently have a Next.js app that is written in Javascript, but I am looking to transition to writing new code in Typescript. To add Typescript to my project, I tried creating a tsconfig.json file at the project root and then ran npm install --save-dev ...

Creating a dynamic state management system for multiple Collapse components can be achieved by utilizing

I am trying to create a Collapse menu from array data, Currently, when I click on any menu all sub menus expand I believe my issue lies in not being able to set a unique "open" state for each Main menu I want to avoid assigning a "state" to accommodate ...

Struggling to dynamically update array values by comparing two arrays

I am faced with a scenario where I have two arrays within an Angular framework. One of the arrays is a regular array named A, containing values such as ['Stock_Number', 'Model', 'Type', 'Bill_Number'] The other arr ...

Executing the outer function from within the inner function of a different outer function

Imagine this scenario: function firstFunction() { console.log("This is the first function") } secondFunction() { thirdFunction() { //call firstFunction inside thirdFunction } } What is the way to invoke firstFunction from thirdFunction? ...

Encountering a Console warning while working with the Material UI menu. Seeking advice on how to resolve this issue as I am integrating HTML within a text

Caution: PropType validation failed. The prop text provided to LinkMenuItem is invalid as it should be a string, not an object. Please review the render method of Menu. Below is the code snippet: var menuItems = [ // text is not valid text { route: &ap ...

Utilize Angular 5 to implement URL routing by clicking a button, while also preserving the querystring parameters within the URL

I have a link that looks like this http://localhost:4200/cr/hearings?UserID=61644&AppID=15&AppGroupID=118&SelectedCaseID=13585783&SelectedRoleID=0 The router module is set up to display content based on the above URL structure { path: & ...

What is the best method to display a tooltip for a disabled radio button within a set of radio buttons?

Is there a way to disable a specific radio button based on a condition and display a tooltip only for that disabled button? https://i.stack.imgur.com/niZK1.png import {Tooltip} from '@mui/material'; <Tooltip titl ...

typescript defining callback parameter type based on callback arguments

function funcOneCustom<T extends boolean = false>(isTrue: T) { type RETURN = T extends true ? string : number; return (isTrue ? "Nice" : 20) as RETURN; } function funcCbCustom<T>(cb: (isTrue: boolean) => T) { const getFirst = () => ...

Change the right border style for the second and third ToggleButtons in the ToggleButtonGroup

I've been working on this for a few hours now and I can't seem to get it right. Currently, I'm using Mui v5 and trying to style the ToggleButtons to look like regular MUI buttons. So far, I was able to achieve this transformation: https:/ ...

What is the process for updating a particular index in a list?

Currently, I am delving into React by working on a task master app. The concept is simple - each user input becomes a new task in an array of tasks. The app features Add, Delete, and Update buttons for managing these tasks. Everything is functioning smoot ...

What is the best way to implement the Snackbar functionality within a class-based component?

My snackbar codes are not working as expected when I click the "confirm" button. I want the snackbar to appear after clicking the button. Most examples I've seen use functional components, so how can I get the Snackbar to work properly in a class comp ...

Adjust properties based on screen size with server-side rendering compatibility

I'm currently using the alpha branch of material-ui@v5. At the moment, I have developed a custom Timeline component that functions like this: const CustomTimeline = () => { const mdDown = useMediaQuery(theme => theme.breakpoints.down("md")); ...

Is there a way to extract a token from the URL in a Nextjs/React application?

I am currently developing a project that relies heavily on API integration. My front-end interface is built using React and Next.js, while the back-end API is developed with Laravel. Within my front-end page, I have implemented a token in the URL to help ...

Every time a button is clicked on the interface, a new element or button will appear. This functionality is made possible through

Currently diving into a new React.js project as a beginner. I have a little challenge in the code snippet below - looking to add a button that displays "Hello World" every time it's clicked using setState. Can anyone guide me on enhancing the DisplayM ...

Issue with rendering HTML entities in Material UI when passing as props

Encountered a problem with the radio buttons in Material UI. Currently, Material UI accepts value as a prop for the FormControlLabel component. When passing a string with an HTML entity like below, it gets parsed correctly. <FormControlLabel value="fem ...

Error arises on Github when submitting a pull request due to a conflicted package

When facing conflicts in the package.json file while submitting a pull request, what is the best approach to resolve them? I usually attempt using git pull origin, but it tends to generate numerous merge commits. ...

What is the best way to dismiss the modal window in React upon clicking the "Add product" button?

Hello all, I'm having trouble figuring out how to close the modal window in React. I want it so that when the user clicks on the "Add" button, a modal window opens for data input, and then upon clicking the "Add product" button, the window closes imme ...

Is it possible for the Redux inside a React component from npm to clash with the Redux in the container?

I am looking to bundle a React component with npm and incorporate Redux to handle state within the component. If another React project imports my component, will it cause conflicts with the Redux instance of that project? For example: The component code ...

The module located at "c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx" does not have a default export available

I am currently delving into the realm of RxJs. Even after installing rxjs in package.json, why am I still encountering an error that says [ts] Module '"c:/Users//Desktop/iooioi/src/main/webapp/node_modules/rxjs/Rx"' has no default export ...