Home > Net >  React - passing props to parent
React - passing props to parent

Time:04-23

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>
                .....  

CodePudding user response:

Try to pass category as a parameter at the props.passSelectedCategory ( the child component, CategoryWindow doesn't have the visibility of the selectedCategory variable)

CodePudding user response:

 <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.

  • Related