Reputation: 2148
I am trying to pass an object from Parent to Child as described in this article.
I am new to React JS and am probably missing something simple here.
The goal of this is to have a select list of "Industries" that passes the selected industry to a select list of "Categories". The selected Category would then populate a table.
I am getting the error that this.props.selectedIndustry
doesn't exist on compile.
Here is my code:
class CategoryFilter extends React.Component {
constructor(props) {
super(props);
this.state = {
industrySelect: this.props.selectedIndustry
}
console.log(this.props.selectedIndustry)
}
render() {
const { selectedCategory } = this.state;
const categories = utmcategories.filter(function(i) {return i.industry==this.props.selectedIndustry})
return (
<Select options={categories} onChange={this.handleCategoryChange}
/>
);
}
class IndustryFilter extends React.Component {
state = {
selectedIndustry: null,
};
handleIndustryChange = (selectedIndustry) => {
this.setState({ selectedIndustry });
console.log(`Option selected:`, selectedIndustry);
}
render() {
const { selectedIndustry } = this.state;
const industries = utmindustries;
return (
<div>
<Select options={industries}
onChange={this.handleIndustryChange}
autoFocus={true}
/>
<CategoryFilter selectedIndustry={selectedIndustry}/>
</div>
);
}
}
I modified the code to narrow down the issue and made my CategoryFilter this:
function CategoryFilter(props) {
return (
<div>
{props.filteredIndustry}
</div>
)
}
But still got the error:
"Objects are not valid as a React Child."
Upvotes: 0
Views: 793
Reputation: 459
You are initialising selectedIndustry
to null
here:
state = {
selectedIndustry: null,
};
and then passing it in as a prop to <CategoryFilter>
I am getting the error that this.props.selectedIndustry doesn't exist on compile. Here is my code
Not quite sure that the 'error' you are getting is actually an error. Seems like it may be the expected behaviour. Could you please show us the error message exactly?
I would expect this.props.selectedIndustry
to be defined as null
after <CatergoryFilter>
has mounted. You should try initialising it to a value e.g. "Default Industry" and see if that console.log(this.props.selectedIndustry)
in the constructor is printing "Default Industry". If not, I would suspect that the this
context has not been initialised until after the constructor has returned. Try logging this value in the render() method instead.
Upvotes: 1