I have a parent component that contains a modal which I want to show/hide onClick of an element in a child component. How can I now basically call that handler in the parent company from the child component click?
My idea was to somehow provide the handler via the props from the parent to the child:
// parent components
import PlannerDetails from "./PlannerDetails";
import PlannerTools from "./PlannerTools";
import {useState} from "react";
const PlannerWrapper = () => {
const [showTools, setShowTools] = useState(false)
const toolsHandler = () => {
setShowTools(true)
}
return (
<div className="wrapper w-6/6 h-full flex bg-dotted bg-sx-white">
<div className="right-wrapper w-3/6 h-full p-8">
<div className="details-wrapper w-full h-full bg-sx-white-plain rounded-2xl shadow-sx-shadow">
<PlannerDetails/>
</div>
</div>
{showTools ? <PlannerTools/> : null}
</div>
)
}
export default PlannerWrapper
// child component
import imageEdit from "../../assets/images/edit.svg"
const PlannerDetails = (props) => {
return (
<div className="details-wrapper">
<div className="details-head flex border-b-1 border-b-gray">
<div className="text-2xl text-sx-purple-dark p-4">Offer Details</div>
<div className="icon-wrapper flex">
<img src={imageEdit} className="w-4 cursor-pointer"
onClick={props.toolsHandler}/> // <--------- click event here
</div>
</div>
</div>
)
}
export default PlannerDetails
Updated approach
// Parent
import PlannerDetails from "./PlannerDetails";
import PlannerTools from "./PlannerTools";
import {useState} from "react";
const PlannerWrapper = () => {
const [showTools, setShowTools] = useState(false)
const toolsHandler = () => {
console.log('test')
setShowTools(true)
}
return (
<div className="wrapper w-6/6 h-full flex bg-dotted bg-sx-white">
<div className="right-wrapper w-3/6 h-full p-8">
<div className="details-wrapper w-full h-full bg-sx-white-plain rounded-2xl shadow-sx-shadow">
<PlannerDetails toolsHandler={toolsHandler} />
</div>
</div>
{showTools ? <PlannerTools/> : null}
</div>
)
}
export default PlannerWrapper
// Child
import imageEdit from "../../assets/images/edit.svg"
const PlannerDetails = (toolsHandler, ...props) => {
return (
<div className="details-wrapper">
<div className="details-head flex border-b-1 border-b-gray">
<div className="text-2xl text-sx-purple-dark p-4">Offer Details</div>
<div className="icon-wrapper flex">
<img src={imageEdit} className="w-4 cursor-pointer" alt="editTools" onClick={props.toolsHandler}/>
</div>
</div>
</div>
)
}
export default PlannerDetails
CodePudding user response:
You are very close to the answer, You just need to pass the function in your parent component to the child.
like this
<PlannerDetails toolsHandler={toolsHandler} />
the first toolsHandler
is the prop property in the child component, the second toolsHandler
is the function in parents component.