'How can I pass data between two React components, but the two components have no parent-child relationship?
Solution 1:[1]
I know two solutions to this.
The first and preferred one is to pass a exported function of one component as a property to the other component and thus linking them together, like:
import Dispay from './components/Dispay.js'
import Input from './views/Input.js'
<Input pushData={Dispay.pullData}/>
<Dispay/>
Here a working example of this:
https://codesandbox.io/s/pass-data-between-unrelated-components-rr2li?file=/src/App.js
The second method is an easy, although a bit dirty solution.
Use the browsers window object, as all React components can access this object.
In practice this might look like this:
Syncronous (event based):
components/MainComponent.js:
// call the other component's method with some data
window.processData("myDataString")
views/Element.js:
window.processData = function(data) {
// do something with your data like
console.log("MainComponent received data:",data);
}
Asyncronously
//read and write to this object from wherever you like
window.data
Solution 2:[2]
Use Redux by maintaining the states of all child components that you might need in a global store and obtain the data from said store.
https://react-redux.js.org/introduction/getting-started
make sure to use redux toolkit to simplify your setup: https://redux-toolkit.js.org/introduction/getting-started
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Tharindu Kumarasiri |

