简体   繁体   中英

Select with React.JS - dynamically populated options

I am trying to populate select in [stateless component of] React/Redux app as:

const FillSelect = ({team}) => <option value={team.onboardingOrder}>{team.name}</option>

const TeamSelector = ({teams}) => {
  return (
    <select>
      <option value="">All</option>
      {
        teams ? (teams => teams.map(team => <FillSelect team={team} />)) : null
      }
    </select>
  )
}

Teams looks like: {0:{id: 1, name: "Program Management", onboardingOrder: 0, …}, 1: {id: 2, name: "Value Capture", onboardingOrder: 1, …}…} .

It returns an error: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it. in select ... Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it. in select ...

Is this happening because I am using map() ? What is the correct way of doing this?

You're not calling map directly; if teams is truthy, you return a function ( teams => ... ). You probably wanted the line to look like this:

teams ? teams.map(team => <FillSelect team={team} />) : null

Which would yield an array of <FillSelect /> 's.

This works fine:

  return (
    <select>
      <option value="">All</option>
      {
        Object.values(teams).map((team, i) => <option value={team.onboardingOrder} key={i}>{team.name}</option> )
      }
    </select>
  )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM