Reputation: 2087
I have a select dropdown Component as a Child component where the options(list of category) are generated by API on componentDidMount
in the parent Component. When the user selects the option (category), a selected value must be passed back to the parent component.The parent Component performs the get request based on the value selected and passes the result as options (list of products) to another child component having a select dropdown.
I want to keep these child components as stateless function as it can be used in multiple components.
So, the list of categories is passed as props in the select dropdown ----developer tools:
but not on the webpage.
Parent Container
categories() {
return this.props.category && this.props.category.map((category) =>
<option key={category.id} value={category.name} className="textTransform">
{category.name.charAt(0).toUpperCase() + category.name.slice(1)}
</option>
)
}
onChangeOption(e){
if (e.detail === 0){
// console.log(e.target.value);
this.props.productLoad(e.target.value);
}
}
in the render function of parent component
<SelectCategory
changeOption={this.onChangeOption}
fetchCategory={this.categories()}
/>
Child Component(SelectCategory)
import React from 'react'
import { Field,reduxForm } from 'redux-form';
const SelectCategory = (changeOption,fetchCategory) => (
<div className="col-sm-3 col-md-3 col-lg-3 ">
<div className="form-group">
<Field
name="selectCategory"
component="select"
className="form-control"
onClick={changeOption()}
>
<option value="0" disabled>Select Category</option>
{ fetchCategory() }
</Field>
</div>
</div>
)
export default SelectCategory
Upvotes: 0
Views: 2923
Reputation: 2087
I got it worked by using the callback in the parent function
myCallback = (selectedCategory) => {
this.props.productLoad(selectedCategory);
}
And the callback is passed to the child component as props
<SelectCategory
Categories={this.props.category}
callbackFromParent={this.myCallback}
/>
Therefore,in the child component ,on event trigger i called the function onchangeOption
which in turn passes the selected value to the callback present in the parent component.
onChangeOption=(e)=>{
if (e.detail === 0){
this.props.callbackFromParent(e.target.value);
}
}
Upvotes: 0
Reputation: 1021
The child component won't update because you are not updating any of its props:
You should create an additional prop in the child component, called "selectedOption" and pass that from the parent component. Hence, this prop will change and the child component will update.
Hope this helps. Apologies if I misunderstood the issue!
Upvotes: 0