Sharing Data Between React Components
Solution 1:
There are multiple ways to share data between components. You can use one of the following options:
If the component to which you want to pass the data is a child of
SearchForm
component, then you can pass it as aprop
.If you are managing state via redux, you can connect components to the redux store and get the required data from the redux store in your components.
You can also use React's
Context API
to share common data between components that may or may not have a parent-child relationship.If the component that needs the data from
SearchForm
component, is a parent component ofSearchForm
component, you can pass a callback function to theSearchForm
component as aprop
and when data is available inSearchForm
component, call the callback function, received as aprop
, and pass the data as an argument to that callback function.
Solution 2:
I’d do what Yousaf suggested.
SearchForm should have two props: nameservers handleSubmit
(This will make it easy to write a Storybook story and any tests).
Then make a wrapper for SearchForm that does the API call (handleSubmit) and sets nameservers in context. Now nameservers can be accessed elsewhere in the app.
Solution 3:
Ciao, when I want to share data between components I use React-Redux. Lets make an example: Suppose that you want to share data received by server (nameservers). At first install react-redux:
npm install react-redux
npm install redux
npm install @reduxjs/toolkit
Now we have to create the reducer
and the action
:
Lets say you have your component in a folder called "/components/MyComponent". Create a file called MyReducer.js.
/components/MyComponent/MyReducer.js
import { createReducer } from'@reduxjs/toolkit';
const initialState = {
nameservers: undefined,
};
constLoginReducer = createReducer(initialState, {
["SET_NAMESERVERS"]: (state, action) => {
state.nameservers= action.payload.nameservers;
},
})
exportdefaultMyReducer;
Now, on the same folder, createa file called MyAction.js
/components/MyComponent/MyAction.js
export const setNameServers = data => ({
type: "SET_NAMESERVERS",
payload: { nameservers: data }
});
Then create the store
:
On your project root create a folder callled redux
. Inside this create a folder called store
. Then on this folder create a file called index.js.
redux/store/index.js
import { createStore, combineReducers } from"redux";
importMyReducerfrom'../../components/MyComponent/MyReducer';
const reducers = combineReducers({
MyReducer,
});
const store = createStore(reducers);
exportdefault store;
Now on index.js file on root folder lets pass the store already created:
index.js
...
import { Provider } from'react-redux';
import store from"./redux/store";
ReactDOM.render((
<Providerstore={store}><App /></Provider>
), document.getElementById('root') || document.createElement('div'));
We have almost done. On your component (MyComponent) you retrieve data from server. Once you have data, lets dispatch data to share into the store:
/components/MyComponent/MyComponent.js
...
import { useDispatch } from'react-redux';
import { setNameServers } from'./MyComponentAction';
constMyComponent: React.FC = () => {
const [nameservers, setNameservers] = useState([]);
const dispatch = useDispatch();
....
consthandleSubmit = (event: any) => {
...
fetch(`https://dns.google.com/resolve?name=${domain}&type=NS`)
.then(results => results.json())
.then(data => {
setLoading(false);
if (data && data.Answer) {
data.Answer.sort((a: any, b: any) => a.data.localeCompare(b.data));
setNameservers(data.Answer);
dispatch(setNameServers(data.Answer)); // here the magic
}
});
};
};
Done! now you have nameservers on your react redux store and you can easly get it from another component like this:
OtherComponent.js
import { useSelector } from'react-redux';
constOtherComponent: React.FC = () => {
const nameservers = useSelector(state => state.MyReducer.nameservers);
};
And if you log nameservers somewhere in OtherComponent
you will see data retrieved in MyComponent
. Awesome!
Post a Comment for "Sharing Data Between React Components"