I am looking for a simple way to pass a variable (backend_url={backend_url}) to multiple components in React. The way that I am currently using looks very repeated.
<Routes>
<Route exact path="/posts/:username/newPost" element={<CreatePost backend_url={backend_url}/>} />
<Route exact path="/posts" element={<PostList backend_url={backend_url}/>} />
<Route exact path="/posts/:id/" element={<PostDetail backend_url={backend_url}/>} />
<Route exact path="/posts/:id/delete" element={<DeletePost backend_url={backend_url}/>} />
<Route exact path="/posts/:id/update" element={<UpdatePost backend_url={backend_url}/>} />
<Route exact path="/myPosts" element={<MyPosts />} />
</Routes>
Your suggestion on simpler ways would really be appreciated.
Thank you.
CodePudding user response:
You can make use of the React Context system to pass down the backend_url
prop.
Inside backendUrlContext.js
file
import {createContext, useContext} from "react";
const defaultBackendUrlValue = "";
const backendUrlContext = createContext(defaultBackendUrlValue);
export const BackendUrlProvider = backendUrlContext.Provider;
export const BackendUrlConsumer = backendUrlContext.Consumer;
export const useBackendUrl = () => useContext(backendUrlContext);
Inside routes file
import {BackendUrlProvider} from "backendUrlContext";
<BackendUrlProvider value={backend_url}>
<Routes>
<Route exact path="/posts/:username/newPost" element={<CreatePost />} />
<Route exact path="/posts" element={<PostList />} />
<Route exact path="/posts/:id/" element={<PostDetail />} />
<Route exact path="/posts/:id/delete" element={<DeletePost />} />
<Route exact path="/posts/:id/update" element={<UpdatePost />} />
<Route exact path="/myPosts" element={<MyPosts />} />
</Routes>
</BackendUrlProvider>
Then you can access backend_url value inside any route element nested inside BackendUrlProvider
by using the useBackendUrl
hook
import {useBackendUrl} from "backendUrlContext";
function CreatePost() {
const backendUrl = useBackendUrl();
/*
...rest of the logic
*/
}
And this approach will also work in any nested child component which is not a directly nested route.