This is my code.
import React from 'react';
// Assuming this is your JSON array
const jsonArray = [
{ key: 'key1', value: 'value1' },
{ key: 'key2', value: 'value2' },
{ key: 'key3', value: 'value3' },
// add more objects as needed
];
class MyComponent extends React.Component {
render() {
return (
<select>
{jsonArray.map((item, index) => (
<option key={index} value={item.value}>
{item.key}
</option>
))}
</select>
);
}
}
export default MyComponent;
I want to select value2 as defaultValue from a variable.
I tried with keyword value but the select dropdown not working more. It remains fix on the value.
With defaultValue I don’t know how implement it. I don’t know if it is needed the key, the value or both. I don’t know also if defaultValue is near select or in option tag.
3
Answers
Since the
value
key is chosen to represent the value of each option, thendefaultValue
should also correspond to one of thevalue
keys, in your case:If you are using react-select you need to pass the object for select component as
defaultValue
if you are using JSX select pass the value into it
In your case it’s just as bellow
You can memoize the default value like this:
Just make sure to add a
"default": true
property to your JSON data.