Reputation: 3023
I am trying to add dropdownlist in my reactjs project. My data are coming from api which looks something like this.
In dropdown list i have to display colours
and sizeType
in dropdown list.
I tried doing this but it is not working.
const data = [props.data];
return (
<Grid xs={12} className="sort" container>
<DropdownList
style={{ height: "auto" }}
placeholder={props.title}
className="drop-down"
data={data}
/>
</Grid>
Upvotes: 0
Views: 824
Reputation: 10520
If we suppose that props.data
you provided is the actual data that you received from API.
Since the actual data is Object itself we can access the colours
and sizeType
property within them just like this:
const colours = data.colours;
const sizeType = data.sizeType;
Since the colours
and sizeType
itself are string we should make an array of them to pass it to the DropdownList
as the data, so we can do it as below:
const coloursArray = data.colours.split(',');
const sizeTypeArray = data.sizeType.split(',');
NOTE: Keep in mind each array got his unique indexes so we don't have to create a unique id by ourself and the DropdownList
will use it as it unique id for distinction, but the for using best practices we should provide the unique ids for each dropdown and data by using UUID
to keep the distinction much more clear. For more information about UUID
, you can read this post.
NOTE 2: Since the string attribute that we wanted are splitting with ,
we can simply use the comma symbol as the split
function input. You can read more about the split function here.
So this will be the final return that you have provide for your component:
return (
<Grid xs={12} className="sort" container>
<DropdownList
style={{ height: "auto" }}
placeholder={props.title} //Title for colours dropdown
className="drop-down"
data={coloursArray}
/>
</Grid>
<Grid xs={12} className="sort" container>
<DropdownList
style={{ height: "auto" }}
placeholder={props.title} //Title for colours dropdown
className="drop-down"
data={sizeTypeArray}
/>
</Grid>
)
Upvotes: 1
Reputation: 320
At first you should split your colors string to array
const colorsArray = data.colors.split(',');
then pass it like data attribute
return (
<Grid xs={12} className="sort" container>
<DropdownList
style={{ height: "auto" }}
placeholder={props.title}
className="drop-down"
data={colorsArray}
/>
</Grid>
Upvotes: 1