I am using react, currently I need to display a html list, in LocationFinderList
I am initializing Location
elements but Location
does not get the object and instead I get only numeric property as shown in the pictures.
How to fix my script so Location show the name for an object passe from
LocationFinderList`?
Could be an issue with spread operator?
Notes: location in locations
object in LocationFinderList
are defined as properties of an object not as items in an array.
{ 2643743: { name: "London", country: "GB" }, 4119617: { name: "London", country: "US" } }
import React, { PropTypes } from 'react'; import Location from './Location'; const LocationFinderList = ({ locations, onLocationClick }) => ( <ul> {Object.keys(locations).map((location, index) => <Location key={index} {...location} onClick={() => onLocationClick(location.id)} /> )} </ul> ); export default LocationFinderList;
import React, { PropTypes } from 'react'; const Location = ({ onClick, location }) => ( <li onClick={onClick} > {location} </li> ) export default Location;
Answer
Since you are using Object.keys
to map over you will get the keys as a result and hence if you want to pass the object you need to pass it like locations[location]
Change you code to
const LocationFinderList = ({ locations, onLocationClick }) => ( <ul> {Object.keys(locations).map((location, index) => <Location key={index} {...locations[location]} onClick={() => onLocationClick(location)} /> )} </ul> );
And
const Location = ({ onClick, name, country}) => ( <li onClick={onClick} > {name} </li> )