Reputation: 447
So I have a counties.json
file and I have a file with a select input as such:
<FormGroup row>
<Label for="" sm={2}>Site County</Label>
<Col sm={10}>
<Input className="form-control" type="select">
<option>Louth</option>
<option>Dublin</option>
<option>Louth</option>
</Input>
</Col>
</FormGroup>
My goal is to populate the select input with the data in the json file. How can I do this?
Upvotes: 1
Views: 1051
Reputation: 5182
Since you want to load in json data, you will find it helpful to use the json-loader
package. This allows you to import your json data into a variable.
To add the package to your project, do:
npm install json-loader
Once that's been added, and assuming you have a data file called counties.json
, then you can do the following:
import jsonData from './counties.json'
Let's say your json data looks something like this:
{
"counties": [
{ "value": "louth",
"display": "Louth" },
{ "value": "dublin",
"display": "Dublin" }
]
}
Then, you can get your counties from the json data like so:
const counties = jsonData.counties // This is an array
Once you have your array, you can use the array's map()
function to turn each element of the array (which, in this example, is an object with keys value
and display
) into an <option>
. Make sure, though, because you are rendering an array of options, that you provide a unique key for each option. Just using the value
will be sufficient. So, in render()
it will look like this:
<Input className="form-control" type="select">
{ counties.map(c => (<option key={c.value} value={c.value}>{c.display}</option>))}
</Input>
Here is a code sandbox that demonstrates all of this code in action.
Hope this helps!
`
Upvotes: 1