Reputation: 5924
I am trying to get query parameters from my url and use those values to set the selected option value on load. At the moment I have access to two values that match, which are the option text and the query parameter value.
My original thought is to add a variable within my loop that is set by an if statement that checks if the loop value matches the query props value, but I'm being given an error message about an unexpected token. What is possibly wrong with this setup and there is a better way to set up this evaluation and set "select" to the proper option on page load?
Here is the full error message ({selected}
is where the error happens):
ERROR in ./public/components/app/activity-feed/search-form.js
Module build failed: SyntaxError: Unexpected token, expected ... (45:102)
43 | selected = 'selected';
44 | }
> 45 | return ( <option value={category.categoryHashId} {selected}>
Here is my react code where this.props.category
is an array of ids/text for each category that is possible to query and this.props.categoryQuery
is the text value that is currently a query parameter:
<select name="category" className="form-control filter-category">
{ this.props.category.map( (category) => { var selected; if(category.categoryName == this.props.categoryQuery){ selected = 'selected'; } return (
<option value={category.categoryHashId} {selected}>{category.categoryName}</option> ) } ) }
</select>
For example, this.props.categoryQuery
is Blog
and out of the 8 this.props.category.categoryName
array values, Blog
matches and a "selected" string is added
Upvotes: 1
Views: 1028
Reputation: 4008
You cannot write a prop for an element the way you are doing: <tag {someValue}/>
.
Instead, pass a value
property to the select
element and a defaultValue
to the option
elements:
const {
category,
categoryQuery
} = this.props;
const selectedCategory = category.find((val) => {
return val.categoryName === categoryQuery;
})
return (
<select
name="category"
className="form-control filter-category"
value={selectedCategory.categoryHashId}
>
{category.map((cat) => {
return (
<option
key={cat.categoryHashId}
defaultValue={cat.categoryHashId}
>
{cat.categoryName}
</option>
);
})}
</select>
);
Sidenote: You should not use the categoryName
for identification/comparison/selection if you have a unique categoryHashId
. When the user selects the category, use this instead of the name. You might want to review a bit your data structure for more efficiency.
I wrote this example to match your need, but if you use a hashId
inside your categoryQuery
you can skip the .find()
step.
Upvotes: 2