React Router Dom v6: Scroll To Top on Route Change [duplicate] - scroll

This question already has answers here:
react-router scroll to top on every transition
(35 answers)
Closed 11 months ago.
I made a website on Reactjs and I have linked various pages using 'react-router-dom v6'. Whenever I transition from one page to another, the second page always loads on the current location instead of the top. I have tried many tutorials and solutions but they all are valid till v5 of react-router-dom.

I solved the following issue by creating a wrapper function and wrapping it around all the routes.
Follow the following steps:
1: You need to import the following:
import {Routes, Route, BrowserRouter as Router, useLocation} from 'react-router-dom';
import {useLayoutEffect} from 'react';
2: Write a wrapper function just above the "App" function:
const Wrapper = ({children}) => {
const location = useLocation();
useLayoutEffect(() => {
document.documentElement.scrollTo(0, 0);
}, [location.pathname]);
return children
}
3: Now wrap your routes within the wrapper function:
<BrowserRouter>
<Wrapper>
<Navbar />
<Routes>
<Route exact path="/" element={<Home/>} />
<Route path="/Products" element={<Products/>} />
<Route path="/Login" element={<Login/>} />
<Route path="/Aggressive" element={<Aggressive/>} />
<Route path="/Attendance" element={<Attendance/>} />
<Route path="/Choking" element={<Choking/>} />
<Route path="/EmptyCounter" element={<EmptyCounter/>} />
<Route path="/FaceMask" element={<FaceMask/>} />
<Route path="/Fainting" element={<Fainting/>} />
<Route path="/Smoking" element={<Smoking/>} />
<Route path="/SocialDistancing" element={<SocialDistancing/>} />
<Route path="/Weapon" element={<Weapon/>} />
</Routes>
<Footer />
</Wrapper>
</BrowserRouter>
This should solve the issue.

Related

Added 'search function' using React-admin package, but not working, why?

I am using React-admin to create a customer dashboard where they can find their invoices for all months. Now I would like to add search function to this so that customers can search invoices according to any field,say entity_name.
I am able to add search element on ui, but its not working.
I added search functionality by importing {Filter, TextInput} from React-admin. And I am using data from "ra-data-simple-rest"; and running sever on port 5000 in my local machine.
Here is my code:
const InvoiceFilter = (props) => (
<Filter {...props}>
<TextInput source="entity_name" alwaysOn />
</Filter>
);
const InvoiceList = (props) => {
return (
<List {...props} filters={<InvoiceFilter />}>
<Datagrid>
<TextField source="id" />
<TextField source="entity_name" />
<DateField source="period_start" />
<DateField source="period_end" />
<TextField source="total" />
</Datagrid>
</List>
);
};
You should use proper components for the filter function.
the filters props is for FilterForm
<FilterForm filters={postFilters} />
Placing the filters props in List component is not doing anything.
Create proper filter and pass it to a proper component like shown in the documentation here
Based on the docs, you could try:
const invoiceFilters = [
<TextInput source="entity_name" alwaysOn />
);
const InvoiceList = () => {
return (
<List filters={invoiceFilters}>
<Datagrid>
<TextField source="id" />
<TextField source="entity_name" />
<DateField source="period_start" />
<DateField source="period_end" />
<TextField source="total" />
</Datagrid>
</List>
);
};

Not giving Content when using React-Router-Dom

In this code I have navigated Email.js to Password.js.it is working properly but when after it navigated to Password.js I have navigate to Country.js but it is not showing anything because the path which I have given is /country but it take /Password/Country and when in path I am giving /Password/Country then it is redirecting to /Password/Password/Country.
<Routes>
<Route exact path="/" element={ <Email/> }/>
<Route exact path="Password" element={ <Password/>}/>
<Route exact path="Type" element={ <Type/> }/>
<Route exact path="/Country" element={ <Country/> }/>
</Routes>
You need to use a relative path, like so:
<Routes>
<Route exact path="/" element={ <Email/> }/>
<Route exact path="Password" element={ <Password/>}/>
<Route exact path="Type" element={ <Type/> }/>
<Route exact path="Country" element={ <Country/> }/>
</Routes>

React Router - need help routing

My problem:
If I open http://example.test/profile/create, the New Profile component does not get loaded. Same with the view and edit routes.
In fact, if I click on a Link to profile/create it displays an empty space beneath the Header component. If I try to go to the above address directly via url or by refreshing the page, it shows 404 page not found error.
The Login and Register components work absolutely fine as does the ProfileList (Clicking on a Link or direct navigation both work fine).
<BrowserRouter>
<div>
<Header />
<Switch>
<Route exact path='/' component={ProfilesList} />
<Route exact path='/login' component={LoginComponent} />
<Route exact path='/register' component={RegisterComponent} />
<Route exact path='/profile'>
<Route exact path='/create' component={NewProfile} />
<Route exact path='/view'>
<Route path='/:id' component={ProfileDetail} />
</Route>
<Route exact path='/edit'>
<Route path='/:id' component={EditProfile} />
</Route>
</Route>
</Switch>
</div>
</BrowserRouter>
PS - The below code worked for http://example.test/create AND for http://example.test/1:
<BrowserRouter>
<div>
<Header />
<Switch>
<Route exact path='/' component={ProfilesList} />
<Route path='/login' component={LoginComponent} />
<Route path='/register' component={RegisterComponent} />
<Route path='/create' component={NewProfile} />
<Route path='/:id' component={ProfileDetail} />
</Switch>
</div>
</BrowserRouter>
I'm using Laravel 7 to run my server. The routes/web.php file looks like this -
<?php
Route::view('/{path?}', 'app');
Here's hoping this helps someone.
The key lay in adding a match.path variable. Firstly my App.js file (the entry
place for my app) -
class App extends Component {
render () {
return (
<BrowserRouter>
<div>
<Header />
<Switch>
<Route exact path='/' component={ProfilesList} />
<Route path='/login' component={LoginComponent} />
<Route path='/register' component={RegisterComponent} />
<Route path='/profile' component={Profiles} />
</Switch>
</div>
</BrowserRouter>
)
}
}
Next the Profiles.js file which is handling the routing for profiles link.
const Profiles = ({match}) => {
return (
<BrowserRouter>
<Switch>
<Route path={`${match.path}/create`} component={NewProfile}/>
<Route path={`${match.path}/view`} render={({match}) => (
<Route path={`${match.path}/:id`} component={ProfileDetail}/>
)} />
<Route path={`${match.path}/edit`} render={({match}) => (
<Route path={`${match.path}/:id`} component={EditProfile}/>
)} />
</Switch>
</BrowserRouter>
)
}
export default Profiles
I am still running into the problem of browser throwing 404s when trying to visit the url manually. I know that the answer lies in this answer by Stijn de Witt - I most likely want to do the catch-all solution that he has proposed, but I don't know how to do that. Can someone help?

Animate route change in react-router-dom switch component

I'm having a really hard time animating the transition from one page to another with react-router-dom. The exmaple is fine but I can't get it to work within a Switch component provided by react-router-dom.
I've tried doing this around the Switch component or inside it but it doesn't do anything (also no warnings or errors in the console).
Example
class Layout extends PureComponent {
render() {
const { account } = this.props;
return (
<div className="MAIN">
<Header image={account.resources.logo} backgroundColor={account.theme} />
<ProgressionBar />
<div className="MAIN__content">
<CSSTransition classNames="fade" timeout={{ enter: 1500, exit: 500 }}>
<Switch key={this.props.location.key} location={this.props.location}>
<Route exact path={`${basePath}start`} component={Start} />
<Route exact path={`${basePath}questions`} component={Questions} />
<Route exact path={`${basePath}comments`} component={Comments} />
<Route exact path={`${basePath}capture`} component={Capture} />
<Route exact path={`${basePath}disclaimer`} component={Disclaimer} />
<Route exact path={`${basePath}finish`} component={null} />
</Switch>
</CSSTransition>
<Footer />
</div>
</div>
);
}
}
CSS
.fade-enter {
opacity: 0.01;
}
.fade-enter.fade-enter-active {
opacity: 1;
transition: opacity 500ms ease-in;
}
.fade-exit {
opacity: 1;
}
.fade-exit.fade-exit-active {
opacity: 0.01;
transition: opacity 300ms ease-in;
}
Try this:
<CSSTransition classNames="test" transitionLeaveTimeout={300}>
<Switch key={this.props.location.pathname} location={this.props.location}>
...
</Switch>
</CSSTransition>
try to rename classNames to transitionName.
and the css .fade-exit also should be .fade-leave if you are using these libraries: https://facebook.github.io/react/docs/animation.html or not?
Thanks #Melounek for the help, the issue resided in that I needed to wrap the CSSTransition in a TransitionGroup as shown in the migration docs of react-transition-group.
Example
class Layout extends PureComponent {
render() {
const { account, location } = this.props;
return (
<div className="MAIN">
<Header image={account.resources.logo} backgroundColor={account.theme} />
<ProgressionBar />
<div className="MAIN__content">
<TransitionGroup>
<CSSTransition
key={location.key}
classNames="fade"
timeout={{ enter: 1000, exit: 1000 }}
transitionEnterTimeout={1000}
transitionLeaveTimeout={1000}
>
<Switch key={location.key} location={location}>
<Route exact path={`${basePath}start`} component={Start} />
<Route exact path={`${basePath}questions`} component={Questions} />
<Route exact path={`${basePath}comments`} component={Comments} />
<Route exact path={`${basePath}capture`} component={Capture} />
<Route exact path={`${basePath}disclaimer`} component={Disclaimer} />
<Route exact path={`${basePath}finish`} component={null} />
</Switch>
</CSSTransition>
</TransitionGroup>
<Footer />
</div>
</div>
);
}
}
Try this:
<CSSTransition key={this.props.location.pathname.split('/')[1]} timeout={500} classNames="fadeTranslate" mountOnEnter={true} unmountOnExit={true}>
<div className="WRAPPER">
<Switch location={this.props.location}>
<Route path="/" exact component={Home} />
<Route path="/blog" component={Blog} />
<Route path="/albumn" component={Albumn} />
</Switch>
</div>
</CSSTransition>
Reference: https://github.com/ReactTraining/react-router/issues/5279#issuecomment-315652492

Golang with React Router?

How do I use React Router with Go?
For example,
I have this in Go:
Echo.Get("/*", *handler which return page with ReactRouter*)
And this in React Router:
React.render((
<Router history={History.createHistory()}>
<Route name="index" path="/" component={Main}>
<Route name="users" path="/users" component={Users}>
<Route name="user" path="/user/:userId" component={User} />
</Route>
<Route path="*" component={NotFound} />
</Route>
</Router>
), document.body)
But I keep getting the index (/) page. All routes behave the same ('/', '/users', '/user/qwe', etc.)
You have to render different routes with new bindings, or handle that binding specifically in your handler function and read out the request object's information.
Echo.Get("/user/:id", getUser)
Echo.Get("/users", listUsers)
Echo.Get("/*", catchAllRemainingCalls)
Hope this helps. Good luck!

Resources