I have 2 react components that need to share a state, react-router shows component A, which takes some inputs and adds it to its state, after the state has been successfully
You can build custom React hooks to share a state
between components, I made one here. You can use it by downloading use-linked-state.js
file.
After importing useStateGateway
hook, declare a gateway in parent component and pass it down to your child components
import {useStateGateway} from "use-linked-state";
const myGateway = useStateGateway({partA:null, partB:null});
return (
<>
>
)
Then you have access shared state between those three components by a custom useLinkedState hook
import { useLinkedState } from "use-linked-state";
export default function ComponentA({gateway}){
const [state, setState] = useLinkedState(gateway);
}
In your logic ComponentA
and ComponentB
would be responsible for their part in shared object {partA:"filled by ComponentA", partB:"filled by componentB"}
.
Finally ComponentPost
post the result if partA
and partB
of shared object were valid.
In this way you can compose components and make connection between them to talk to each other.