i want to send pata from child to parent without using useContext
Answered
Mahid posted this in #help-forum
MahidOP
i have created a ecommerce store and i want to pass data from child to parents maybe using useState
Answered by New Guinea Singing Dog
Just pass the setter into the props of the child function
export function Parent() {
const [num, setNum] = useState(0);
return (
<div>
<p>{num}</p>
<ChildComponent setter={setNum}/>
</div>
)
}
function ChildComponent({setter}: {setter: Function}) {
return (
<button onClick={() => setter(x => x+1)}>Click here</button>
)
}5 Replies
New Guinea Singing Dog
You could create state and pass the setter to child
It's better to use state if it's about immediate parent .. if you are trying to pass multi-level parent/s then you should use context on top parent level [of the hierarchy you want the data to be available for].
@New Guinea Singing Dog You could create state and pass the setter to child
MahidOP
example please right now i am using useContext
@Mahid example please right now i am using useContext
New Guinea Singing Dog
Just pass the setter into the props of the child function
export function Parent() {
const [num, setNum] = useState(0);
return (
<div>
<p>{num}</p>
<ChildComponent setter={setNum}/>
</div>
)
}
function ChildComponent({setter}: {setter: Function}) {
return (
<button onClick={() => setter(x => x+1)}>Click here</button>
)
}Answer
@New Guinea Singing Dog Just pass the setter into the props of the child function
typescript
export function Parent() {
const [num, setNum] = useState(0);
return (
<div>
<p>{num}</p>
<ChildComponent setter={setNum}/>
</div>
)
}
function ChildComponent({setter}: {setter: Function}) {
return (
<button onClick={() => setter(x => x+1)}>Click here</button>
)
}
MahidOP
thank you soo much for this i will keep it in mind i havent tested it yet but lets hope it will work