I would like to know how Downshift can work with an array of objects.
Instead
const items = ["apple", "pear", "orange"]
const items = [{"name" : "apple"}, {"name" : "pear"}, {"name" : "orange"}]
https://codesandbox.io/s/ryw2yzmyzp
import React, { Component } from "react"
import { render } from "react-dom"
import Downshift from "downshift"
const items = [{"name" : "apple"},{"name" : "pear"}, {"name" : "orange"}]
class TypeAhead extends React.Component {
state = {
inputValue: ""
}
render() {
const itemToString = (i) => (
i ? i.name : ''
)
return (
<div>
<Downshift
selectedItem={this.state.inputValue}
onChange={selection => alert(`You selected ${selection}`)}
>
{({
getInputProps,
getItemProps,
getLabelProps,
isOpen,
inputValue,
highlightedIndex,
selectedItem
}) => (
<div>
<input {...getInputProps()} />
{isOpen ? (
<div>
{items
.filter(i => !inputValue.name || i.includes(inputValue.name))
.map((item, index) => (
<div
{...getItemProps({
key: item.name,
index,
item,
style: {
backgroundColor:
highlightedIndex === index
? "lightgray"
: "white",
fontWeight:
selectedItem === item ? "bold" : "normal"
}
})}
>
{item.name}
</div>
))}
</div>
) : null}
</div>
)}
</Downshift>
</div>
)
}
}
render(<TypeAhead />, document.getElementById("root"))
Hi @klapouchy!
Your code looks fine. There's only one small bug in your filter function:
You access inputValue.name but inputValue is just a string. It should rather look like this:
filter(i => !inputValue || i.name.includes(inputValue))
This is a surprisingly common question. We should update the simple example in the README to be an array of objects instead of an array of strings. Would you like to do that @klapouchy?
@kentcdodds I would like to do that, can you please show me how, this will be my first time :smiley:
Thanks @lenaggar, I actually updated the example in the README a few days ago and forgot to close this.