React-router-dom how to update parent state inside route component - javascript

I have a class parent class App containing a navbar and a bunch of routes:
function App() {
const [showNavbar, setShowNavbar] = useState(true);
return (
<>
<MyNavBar show={showNavbar}/>
<Switch>
<Route exact path='/child' component={() => <ChildPart setter={showNavbar}/>}/>
<Route> ... //other routes
</Switch>
</>
)
}
function ChildPart(props) {
const [data, setData] = useState("");
// hide navbar
useEffect(() => {
console.log("child init"); // this got printed twice
props.setter(false);
}, [props.setter]);
// get data at first mount;
useEffect(()=>{
setData(api.loadUserInfo());
}, []);
return (<div>
Data here: {data}
</div>)
}
What I want to achieve is to have navbar change based on which page a user is currently at.
For example, hide navbar when use is visiting /child
But by implementing it this way, the ChildPart seems got mount and unmount for twice since the parent is rendered and rotues are also a part of the App.
This causes unnecessary API calls inside the child component.
Is there any way to address this?

Have you considered adding the Navbar as a component in the Routes, instead of using the state to decide if the navbar should be visible or not?
<Switch>
<Route exact path='/child' component={ChildPart}/>
<Route path="">
<MyNavBar />
<Home />
</Route>
</Switch>

If hiding one (MyNavBar) component by navigating to one (or more) urls is a goal, something like this could work. Unfortunatelly negative lookup (regex) is not supported by react router so we can't use something like this (?!child).
Another thing which you can do is making MyNavBar aware of current url by wrapping it withRouter HOC or using useLocation hook. Than, you can do your logic in MyNavBar depending on url.

Related

React router DOM : Switch not working if child element isnt a route

I'm facing an issue im not able to comprehend. I'm working on a React codebase and we started having too much Routes, so i decided to refactor it a little bit. There is some logic to determine if we should redirect to a route that will check if you're authenticated, and if not will redirect you to the sign in page. We also have basic routes without that mechanism that just display a component ( for every page that doesnt need authentication like sign in, forgot password etc. )
I've decided to abstract that logic in a different component, that will ultimatley render a Route. As a first step in that direction, i decided to wrap the rendering of every route in a single component, instead of having the whole logic just laying down there.
Here's the code for the routes:
<Switch>
{Object.values(userRoutes).map((route: SanitizedRoute) => (
<RouteController route={route} key={route.PATH} />
))}
</Switch>
RouterController.tsx
return (
<Route
path={props.route.PATH}
exact={props.route.EXACT}
render={() => {
return <Layout>{props.route.COMPONENT}</Layout>;
}}
/>
);
All the information for the Route component is passed down as a prop. This is where i start getting problems. If i try to access /path_b what is rendered is the first element of my userRoute array, eventhough the Route doesn't match; /path_b or /path_c or /path_whatever will always render the compononent defined for /path_a.
Accessing any path actually returns the /path_a component as if it was the only one present in my Switch component.
If i were to replace the RouteController component by its content as such :
<Switch>
{Object.values(userRoutes).map((route: SanitizedRoute) => (
<Route
path={route.PATH}
exact={route.EXACT}
key={route.PATH}
render={() => {
return <Layout>{route.COMPONENT}</Layout>;
}}
/>
))}
</Switch>
Then everything would work fine as expected. Wrapping my RouteController with a Switch component is also working fine - although im not sure about the side effect of having a Switch per route ?
{Object.values(userRoutes).map((route: SanitizedRoute) => (
<Switch key={route.PATH}>
<RouteController route={route} />
</Switch>
))}
My questions are:
Why isn't it possible to wrap all of those routes in a single ?
Is there some props from the component i should manually pass down to the component via my ?
I know that the is used to render the first route that match the path. Does having multiple kind of defeat the purpose of using a in the first place ?
Here's a Sandbox to display this behavior : https://codesandbox.io/s/react-router-dom-switch-test-forked-sqc98
I wrapper 1 route in a component. When using the wrapper nothing work. If i copy paste the wrapper content inside the Switch, it does.
Why isn't it possible to wrap all of those routes in a single
<Switch>?
This is because of how the Switch component works, it renders the first child <Route> or <Redirect> that matches the location.
Switch
The RouteController component is neither, so it's not involved in matching, and in fact only first component will be rendered. This is why you see only the first route rendered regardless of path.
Is there some props from the <Switch> component I should manually
pass down to the <Route> component via my <RouterController>?
It's possible to move/define a path prop (and any other "route" prop) on the RouteController the Switch may use for path matching, but this is ill-advised and not a documented use case of the Switch and Route components.
I know that the <Switch> is used to render the first route that
match the path. Does having multiple <Switch> kind of defeat the
purpose of using a <Switch> in the first place?
Yes, if you are rendering multiple Switch components, each with only a single Route component then they aren't really switching routes at this point and you're relying on the inclusive route matching of any wrapping router, or exclusively matching in the case of any other wrapping switches.
Solution
Instead of trying to map routes into your RouterController component and dealing with the issues of what is directly composing what, have your RouterController consume all the routes as a prop, and render them into a single Switch component.
RouterController.tsx
const RouterController = ({ routes }) => {
// any component business logic
return (
<Switch>
{routes.map((route: SanitizedRoute) => (
<Route
path={route.PATH}
exact={route.EXACT}
key={route.PATH}
render={() => <Layout>{route.COMPONENT}</Layout>}
/>
))}
</Switch>
);
};
...
<RouterController routes={Object.values(userRoutes)} />

How to update component that is being rendered on route of 'react-router-dom'?

When my App runs componentDidMount() I fetch the data
async componentDidMount() {
try {
let players = await playersDAO.read();
this.setState({ players: players });
} catch (e) {
console.log(e);
}
}
Then show it on a component that is being rendered by Route from react-router-dom
<BrowserRouter>
<Switch>
<Route
key="players"
path="/players"
render={() => <Players rows={this.state.players} />}
/>
</Switch>
</BrowserRouter>
I don't know why, but when the data is fetched the component do not update. Maybe(there's a large chance) I'm doing something wrong, but can anyone help me with it?
Off-topic: I use the render propriety of Route, because i need to pass props for my component, anyone knows a better way of doing so?
You can call the route after setting state using history.push('/players').

What are the standard patterns for using the react componentDidMount() method to fetch api data for multiple routes?

I am trying to piece together how I should be using the componentDidMount() method.
I am using react, and react router
Backend is firebase cloud functions and firestore
I have three routes including the parent component (/) - then /someLocation, and /someItem. In addition, it is possible to go to say /someLocation/someItem. Initially, I am fetching and setting the state with a get request in componentDidMount(). The issue is that when I refresh the child component, I lose state.
From my research I gather that I have two options or a combination of the two (excluding hash router)
Store data in local storage (probably ok for fetching a single record)
Make a get request every time the page is refreshed which makes sense for the parent component
What is the most common design pattern for routing in react for these cases, and what requests should be contained in the parent's componentDidMount method?
Thanks! Any direction, tips, tricks or guidance is greatly appreciated.
render() {
const { jobs } = this.state
const getJobPost = (props) => {
let slug = props.match.params.slug
let job = jobs.find((job) => job.slug === slug)
return <JobPost {...props} job={job} isLoading={this.state.isLoading} />
}
return (
<Switch>
<Route
exact
path="/"
render={(routeProps) => (
<MainJobBoard
countryFilter={this.countryFilter}
handleFilter={this.handleFilter}
filterValue={this.state.filterValue}
isLoading={this.state.isLoading}
jobs={jobs}
{...routeProps}
/>
)}
/>
<Route exact path="/:location/:slug" render={getJobPost} />
</Switch>
)
}

router changed but component does not rerender

I'm using react-router v4 and redux. I have a react-router event like so
//src/App/components/common/Notifications
onCommentClick = (id) => {
this.props.history.push(`/dashboard/${id}`)
}
It will change the browser url, my route is setup correctly I guess
//src/App/containers/dashboard/user/NotificationDetail
renderUserRoute() {
return (
<Switch>
<Route exact path="/dashboard" component={UserAreaGuarded} />
<Route exact path="/dashboard/:id" component={NotificationDetail} />
</Switch>
)
}
but the problem is redux doesn't seem to rerender my container component, I need to refresh to get the right content.
I created a repo just to demo this issue https://github.com/thian4/hoc-redux, been stuck for so long for this, couldn't find any clue why it doesn't rerender.
The problem was not with the router, the NotificationDetail component invokes fetchNotification only in componentDidMount. As you are rendering the route components with the Route component prop, the NotificationDetail route component is mounted only once and then merely updated on every re-render.
There are two ways to fix this...
In NotificationDetail, do the fetchNotification stuff in componentDidUpdate instead of componentdidMount, simply rename the method. This approach is better.
Use a stateless component as the value of component prop in dashboard\index.js:
renderUserRoute() {
return (
<Switch>
<Route exact path="/dashboard" component={UserAreaGuarded} />
<Route exact
path="/dashboard/:id"
component={props => <NotificationDetail {...props} />} />
</Switch>
)
}
This will make React-Router render a new route component every time the route changes. Obviously this has performance issues over #1.
Unrelated to this, please add a key={i} on this line in Notification.js to fix the dreaded Each child in an array or iterator should have a unique "key" prop. warning.
Hope this helps.

React router: component not updating on url search param change

I have a React application that uses URL search params. Depending on the value of the search parameter v, the component is supposed to show different content.
A possible URL might look like this:
http://localhost:3000/hello?v=12345
Once the v query parameter changes in the URL, I would like my component to update.
http://localhost:3000/hello?v=6789
I'm using using react-router in my App component to display the different components depending on the route. The App component is wrapped into a BrowserRouter component.
render() {
return (
<Switch>
<Route path="/hello" component={Hello}></Route>
<Route path="/" component={Home}></Route>
</Switch>
);
}
If a user clicks on something and the URL search param v changes, I would like the component to display different content. Currently, the URL search param does change, but the component doesn't render again. Any ideas?
As #forJ correctly pointed out, the main idea is to make the component re render once the URL parameters change. I achieved it like so:
render() {
return (
<Switch>
<Route path="/hello" render={() => (<Hello key={this.props.location.key}/>)}></Route>
<Route path="/" component={Home}></Route>
</Switch>
);
}
this.props.location.key changes every time the URL changes (also if the query params change). So if you pass it as props to the component, then the component re renders on URL param changes, even though the base URL (the URL without the URL params) hasn't changed.
I also had to use the withRouter higher order component to make it work.
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Hello));
You have not provided enough information so I cannot be 100% sure where you are going wrong but I can see 1 problem right now in your code. First, you have to let the router know that you will be using parameters. So for example below code
render() {
return (
<Switch>
<Route path="/hello/:yourParam" component={Hello}></Route> // you need the colon here
<Route path="/" component={Home}></Route>
</Switch>
);
}
The above will tell the route that parameter called yourParam will be accessible from the URL
Then it has to be accessed in your component and put into render function somehow (use it to retrieve data from database to render data, just render params directly, etc).
For example below
render(){
<div>
{this.props.match.params.yourParam}
</div>
}
This way, your component will re-render everytime there is param change.
EDIT
Since you want to use query instead of parameter, you would have to retrieve it by going. this.props.match.query.v. You would still have to make sure that variable is rendered depending on query change
If you use useEffect hook make sure to have [props.match.params] instead of empty array []
useEffect(() => {
(async () => {
// Fetch your data
})();
}, [props.match.params]) // <-- By this it will get called when URL changes
of course for class components this.props.match.params

Categories

Resources