BennKingy
BennKingy

Reputation: 1583

How to pass object down into react component?

React newbie here! I have an object cats which contains a list of lat long cords for cat locations. I am trying to pass the object down into the MapContainer component like so:

<MapContainer cats={cats} /></div>

MapContainer component:

export class MapContainer extends Component {

  constructor(props) {
    super(props);

    this.state = {
      cats: // this should come from the parent component
    }
  }

  displayMarkers = () => {
    return this.state.cats.map((cat, index) => {
      return <Marker key={index} id={index} position={{
       lat: cat.latitude,
       lng: cat.longitude
     }}
     onClick={() => console.log("You clicked me!")} />
    })
  }

  render() {
    return (
      <Fragment>
        <Map
          google={this.props.google}
          zoom={8}
          style={mapStyles}
          initialCenter={{ lat: 47.444, lng: -122.176}}
        >
          {this.displayMarkers()}
        </Map>
      </Fragment>
    );
  }
}

How can I adjust my class component to take the cats object in?

Upvotes: 0

Views: 66

Answers (3)

D.matoschaves
D.matoschaves

Reputation: 36

Probably you don't need to convert the props cats into state in your MapContainer component, and instead just use the object / array as it is, but if you wanted to have it as state, you could do:

constructor(props) {
    super(props);

    this.state = {
      cats: props.cats
    }
  }

Upvotes: 0

klugjo
klugjo

Reputation: 20875

A few remarks:

  • You can access the properties passed to a child component through props in the constructor or this.props in other lifecycle functions
  • It is considered bad practice to copy the props value to the state.

So just access cats from props directly:

export class MapContainer extends Component {
  displayMarkers = () => {
    return this.props.cats.map((cat, index) => {
      return <Marker key={index} id={index} position={{
       lat: cat.latitude,
       lng: cat.longitude
     }}
     onClick={() => console.log("You clicked me!")} />
    })
  }

  render() {
    return (
      <Fragment>
        <Map
          google={this.props.google}
          zoom={8}
          style={mapStyles}
          initialCenter={{ lat: 47.444, lng: -122.176}}
        >
          {this.displayMarkers()}
        </Map>
      </Fragment>
    );
  }
}

Upvotes: 1

Ashkan Pourghasem
Ashkan Pourghasem

Reputation: 748

Generally deriving state from props is not what you want. Why not use the prop directly? But if you really must do it like that (i.e. to initialize the state using the props that come in) you should check out the getDerivedStateFromProps lifecycle hook:

getDerivedStateFromProps React.js

Upvotes: 1

Related Questions