So I am aware there are many similar questions on here however all the solutions involve using useRef
which I would rather not do.
I have the following situation (which I have simplified):
const Parent = () => {
return (
<div>
<button>Click</button>
<Child>
</div>
)
};
.
const Child = () => {
const doThing = () => {
console.log("I ran")
}
return (
<div></div>
)
};
In reality, my Parent Component contains a button and my child component contains folders and within those folders I have files. I want to collapse all of those folders by clicking on the Button within the parent. (Also with the way the components are laid out it wouldn't make sense to move the button into the child)
To achieve this without refs I know I can do the following:
const Parent = () => {
const [wasTriggered, setWasTriggered] = useState(false)
const clickFunction = () => {
setWasTriggered(true)
}
const changeBackToFalse = () => {
setWasTriggered(false)
}
return (
<div>
<button onClick={clickFunction} >Click</button>
<Child wasTriggered = {wasTriggered} changeBackToFalse={changeBackToFalse}>
</div>
)
};
.
const Child = ({wasTriggered, changeBackToFalse}) => {
const doThing = () => {
console.log("I ran")
}
useEffect(()=>{
if (wasTriggered) {
doThing()
changeBackToFalse()
}
},[wasTriggered])
return (
<div></div>
)
};
But this is tedious and seems like I'm passing stuff back on forth simply to achieve what I want.
What I want is some way of triggering the method within the child from the parent. I apologise if this is either incredibly simple or impossible but with my limited knowledge of React, I'm not sure which it is, Thanks.