What I want to do is select an item from the ListBox and display it in the same WebPage. The ListBox renders correctly, but when I try to Output the selected value, it shows target undefined. Refer comments in code.
I tried using event.target.value to retrieve the value selected which has always worked for me so far, but it says event.target is undefined and the value is inaccessible.
Note : I tried using Grommet for this app for styling, "List", "Box", "ListItem" are all grommet components.
Any help will be highly appreciated.
import React, {Component} from "react";
import Box from "grommet/components/Box";
import List from "grommet/components/List";
import ListItem from "grommet/components/ListItem";
const lb = [];
class ListBox extends Component{
state = {
products: [ //Array of Products
"Product1",
"Product2",
"Product3"
],
selected: null //State Variable where selected item will be stored
};
contents () {
for (let i = 0; i < this.state.products.length; ++i){
lb[i] =
<ListItem justify = "between" key = {i}>
<span>
{this.state.products[i]}
</span>
</ListItem>
}
}
itemSelected (event) {
console.log(event.target); //SHOWS TARGET UNDEFINED in Console Window
let temp = {
selected: event.target
}
this.setState(temp);
}
render () {
this.contents();
return (
<Box>
<List
selectable={true}
onSelect = { //The function call on selecting an item
(event) => {
this.itemSelected(event);
}
} >
{lb}
</List>
<p>Selected Product : {this.state.selected}</p>
</Box>
);
}
}
export default ListBox;
grommet give you selected item index not event. please check official document.
itemSelected (index) {
console.log(index);
let temp = {
selected: this.state.products[index]
}
this.setState(temp);
}