'React - passing props to parent
I can't seem to get it to work. all i need is to pass a single value, selectedCategory. the error i'm getting:
Cannot read properties of undefined (reading 'passSelectedCategory') (in the child component)
Child:
const CategoryWindow =(props)=> {
const categories = ["h", "a", "s", "o"]
return (
<div className="categories-div">
{categories.map(category =>
<button className={"category-btn " + `${category}`}
key={category}
value={category}
onClick={props.passSelectedCategory(selectedCategory)} <----
>
<h2>{category}</h2>
</button>
)}
</div>
)
}
parent:
const Main =()=> {
const [showElement, setShowElement] = useState([1][0][0]);
const [selectedCategory, setSelectedCategory] = useState();
return (
<>
<main className="main">
<div>
<div>
<CategoryWindow
passSelectedCategory={setSelectedCategory} <---
/>
</div>
.....
Solution 1:[1]
Try to pass category
as a parameter at the props.passSelectedCategory
( the child component, CategoryWindow
doesn't have the visibility of the selectedCategory
variable)
Solution 2:[2]
<button className={"category-btn " + `${category}`}
key={category}
value={category}
onClick={() => props.passSelectedCategory(category)}
>
<h2>{category}</h2>
</button>
Everything in your code is perfect you just need to change your onClick function as I mentioned above.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jonathan Obino |
Solution 2 | Ubaid Hussain |