I'm completely new to React so I'm not sure if I have the right title.
I have two component, Header and Product. I want to render the content of Product component when a button is clicked in Header, but I'm not sure how to "pass" this function from Header to Product. Would anyone like to help? Here's my code.
In Header
import React from "react";
import handlePage from "./ProductList";
//I'm trying to import the function, there was no error so I'm not sure if it's success or not.
const Header = () => {
return (
{/* some content is skipped */}
<Nav onClick={()=>handlePage('women');})> Women </Nav>
{/* more content is skipped */}
}
In Product
const Product= ()=>{
const [product, setProduct] = useState();
const handlePage = () => {
return setProduct();
// Expect to return empty content once clicked
};
return(
{/* some content is skipped */}
)
}
Thanks everyone for help!
CodePudding user response:
The simplest way to pass data and functions between components is using the props field which looks something like
<Header prop1={} prop2={} />
const Header = (props) => {
//props.prop1 and props.prop2 can now be used in this scope
}
A good practice is to pass handler functions from parent to child node. This way if a sibling node also has to utilize the same handler, it can be passed down as props.
CodePudding user response:
You can try something like this:
Header component
import Product from "../Product";
import { useState } from "react";
//import handlePage from "./ProductList";
const Header = () => {
const [prodType, setProdType] = useState('')
return (
<div>
<label onClick={() => setProdType('Women')}>Women</label>
<Produto prodType={prodType} />
</div>
)
}
export default Header
Product component
const Product = (props) => {
return(
<div>{props.prodType}</div>
)
}
export default Product