Tjorriemorrie
Tjorriemorrie

Reputation: 17282

How to access current element on event in react?

Code:

class Locations extends React.Component {
    render() {
        let { home, work, onChange } = this.props;
        return <div className="controls">

            <GoogleMapLoader
                containerElement={
                    <div
                        {...this.props}
                        style={{
                            height: '100%'
                        }} >
                    </div>
                }
                googleMapElement={
                    <GoogleMap
                        ref="map"
                        defaultZoom={15}
                        center={{
                            lat: 47.6205588,
                            lng: -122.3212725,
                        }}
                    >
                        <SearchBox
                            ref="searchBoxHome"
                            placeholder="Home"
                            controlPosition={google.maps.ControlPosition.TOP_LEFT}
                            onPlacesChanged={onChange(this.refs.searchBoxHome.getPlaces(), 'home')}
                        />
                        ...

Error:

TypeError: this.refs.searchBoxHome is undefined

I'm not sure how to properly bind the method on the element to the onChange function that I pass in.

Action:

export const changeAddress = (places, place) => {
    return {
        type: 'CHANGE_ADDRESS',
        places,
        place
    }
};

Upvotes: 1

Views: 2498

Answers (2)

Oleksandr T.
Oleksandr T.

Reputation: 77502

You can try use arrow function, like this

<SearchBox
  ref="searchBoxHome"
  placeholder="Home"
  controlPosition={ google.maps.ControlPosition.TOP_LEFT }
  onPlacesChanged={
    () => onChange(this.refs.searchBoxHome.getPlaces(), 'home')
  }
/>

Upvotes: 1

Yuya
Yuya

Reputation: 2311

The event is passed by default to the function, which you can access the element by event.target.

onChange(element, home) {
  ...
}

and

<SearchBox
  ref="searchBoxHome"
  placeholder="Home"
  controlPosition={google.maps.ControlPosition.TOP_LEFT}
  onPlacesChanged={event => onChange(event.target, 'home')}
/>

Upvotes: 4

Related Questions