Reactjs - Update state of parent after obtaining calculated value from another component function

3624 views reactjs
-3

In my React App, I have a text box where users can type location in a Google Autocomplete box - LocationInput.

import React, { Component } from 'react'
...
import LocationInput from './location-input'
...


change = (what, e) => this.setState({ [what]: e.target.value })
....
      render() {
        let {
          location,
          country,
      ...
    } = this.state

...
...
<LocationInput value={location} change={this.change} />

In LocationInput, the county/district is calculated based on what was typed by the user.

This is done in getDistrict(place) but right now I am just console logging it as I do not know how to pass it back as the value of value={location}

import { getDistrict } from '../../utils/edit-profile-utils'

const LocationInput = ({ value, change }) => {
  return (
  <div className="edit_location_div">
    <Autocomplete
        className="locationInput my2"
        onPlaceSelected={(place) => {
          console.log(place)
          console.log(getDistrict(place))
        }}
        placeholder="Enter Nearest MAJOR City"
    />
  </div>
  )
}

In the above component getDistrict(place) returns the district/county. I want to pass this back to update the state of LocationInput value={location}.

How to update the state of the <LocationInput value={location} with the result of function - getDistrict(place). Also, will this cause an infinite loop.

answered question

2 Answers

4

You pass the new location to the change handler:

    onPlaceSelected={(place) => {
      change(getDistrict(place))
    }}

This will call the change function in the outer component and update the state. It shouldn't cause an infinite loop unless for some reason onPlaceSelected gets called again automatically.

posted this
8

why not just have the change function work like:

change = location => this.setState({ location })
....
render() {
   return <LocationInput value={this.state.location} change={this.change} />
}

and then in the child

const LocationInput = ({ value, change }) => {
  return (
  <div className="edit_location_div">
    <Autocomplete
        className="locationInput my2"
        onPlaceSelected={ place => {
          change(getDistrict(place))
        }}
        placeholder="Enter Nearest MAJOR City"
    />
  </div>
  )
}

of course I am making the assumption that the "onPlaceSelected" returns the same data-type as the one stored in the state.

posted this

Have an answer?

JD

Please login first before posting an answer.