Reputation: 565
My parent component looks like:
<div>
<Dropdown items={companiesData} handler={handleClick} />
....//More stuff
</div>
companiesData is an array of items with id, companyName etc.
I am creating my dropdown this way:
const Dropwdown = ({ items, handler }) => {
return (
<select onChange={handler}>
{items.map(({ id, value, companyName, companyType }) => (
<option
key={id}
value={value}
>
{`${companyName}, ${companyType} `}
</option>
))}
</select>
)
}
I know that from the handleClick
function I can access e.target.value
and get the value of the dropdown, but what if I want to get the whole object of that selected value (e.g. containing id, value, companyName etc.)and pass it back to the parent component?
Upvotes: 0
Views: 996
Reputation: 13692
Another option (if you don't want to do filtering) is to simply send e.target
to your handler instead of e.target.value
.
In your handler, retrieve the info you need like this:
const parentHandler = target => {
const targetOptions = target.options;
const selectedValue = target.value;
console.log("selected value", selectedValue);
console.log("all html options array", targetOptions);
console.log("selected option html", targetOptions[target.selectedIndex]);
console.log(
"selected option name",
targetOptions[target.selectedIndex].getAttribute("name")
);
};
see a demo here
Upvotes: 0
Reputation: 1182
in Dropdown, add value property to select and use the id like value={this.state.selectedValue}.
So you will have that value in ev.target.value.
Then, in your parent, you can do something like: companiesData.filter(company => company.id === ev.target.value)
. And you have the info there.
and of course set the selectedValue (using hooks or normal setState)
Upvotes: 1