'Dropdown should render with Data, But getting Empty Dropdown using React
I need to Render a list of Data in the Dropdown, But I am getting Empty Dropdown without any Data... Can Anyone help me out this, Thanks in Advance...
const Dropdown = () => {
const data = inputs;
//console.log(data.purpose);
return (
<select >
<option>Select an Option</option>
{data.purpose.map((items)=>(
//console.log(items.value);
<option>{items.value}</option>
))}
</select>
</div>
</div>
)
}
export default Dropdown
Here is the Data Component
export const inputs = {
"purpose": [
{
"locale": "EN",
"code": "CRP",
"value": "Credit Card Payment"
},
{
"locale": "EN",
"code": "SRP",
"value": "Educational Support"
},
{
"locale": "EN",
"code": "KRP",
"value": "Family Support (Workers uninons)"
},
Solution 1:[1]
First of all, your JSX code has unmatched divs (you're closing two divs after select but not opening them).
return (
<div>
<div>
<select>
<option>Select an Option</option>
{data.purpose.map(items => (
// console.log(items.value);
<option>{items.value}</option>
))}
</select>
</div>
</div>
);
You also need to pass in a key (unique value per array item) to the parent element returned by your map function ("option" element in this case), so that React can correctly keep track of all mapped elements. In your example, you could use item.value for that purpose.
<option key={items.value}>{items.value}</option>
With these two changes your code should already work, but I would also advise that you eliminate the data = inputs attribution from the component, since it is an unnecessary operation that will run everytime your component renders. Alternatively, you could use the data variable directly from the import (just renaming the inputs variable to data in the import statement). Final code should look something like this:
import { inputs as data } from './data';
const Dropdown = () => (
<div>
<div>
<select>
<option>Select an Option</option>
{data.purpose.map(items => (
// console.log(items.value);
<option key={items.value}>{items.value}</option>
))}
</select>
</div>
</div>
);
export default Dropdown;
And the exports:
export const inputs = {
purpose: [
{
locale: 'EN',
code: 'CRP',
value: 'Credit Card Payment',
},
{
locale: 'EN',
code: 'SRP',
value: 'Educational Support',
},
{
locale: 'EN',
code: 'KRP',
value: 'Family Support (Workers uninons)',
},
],
};
Solution 2:[2]
I think Your data is in json format to use it like javascript object you should parse it then use it.
const Dropdown = () => {
const data = JSON.parse(inputs); /// parsing data here.
//console.log(data.purpose);
return (
<select >
<option>Select an Option</option>
{data.purpose.map((items)=>(
//console.log(items.value);
<option>{items.value}</option>
))}
</select>
)
}
export default Dropdown
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ricardo |
| Solution 2 |
