React Router history on browser's back button - reactjs

I have a home component with a link which loads a display component and in display component i have the same link which loads the display component again.
if user clicks the link many times in Display Component then there will be a lot of router history.i want that when a user clicks the browser back button it should load the home component not all the previous history.
when i use history.replace("/"); in Display component with onClick event then it works only one time back.but again back is resulting the previous history of Display Component
Routes.js
import Home from "./Components/Home"
import Display from "./Components/Display"
<Router>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/:city">
<Display />
</Route>
</Switch>
</Router>
Home.js
<Link to ={`/${city}`} onClick={()=>{dispatch(fetchWeather(city)); }}>Search</Link>
Display.js
<Link to ={`/${city}`} onClick={()=>{dispatch(fetchWeather(city)); }}>Search</Link>

Depending on the version of react router you are using you can just add the replace prop on your Link component in the Display.js file to not push new states on the history stack and instead update the current one.
<Link replace to ={`/${city}`} onClick={()=>{dispatch(fetchWeather(city)); }}>Search</Link>
If you're on an older version where this isn't supported what you can do is have a click handler do this for you
// Display.js file
function Display(props) {
// whatever code you have for this file
const handleViewCity = useCallback((event, city) => {
// prevent the default redirect from happening, were going to manage that ourselves
event.preventDefault()
dispatch(fetchWeather(city))
props.history.replace(`/${city}`)
}, [props.history, fetchWeather])
return (
// your jsx
// keep the href so you get browser builtin functionality like right click "open in new window"
<a href={`/${city}`} onClick={(e) => handleViewCity(e, city)}>Search</Link>
)
}
export default withRouter(Display)
To visualize what would be happening here think of history as a stack of locations. (this is a simple example - pseudo code)
history.push('/city1') // ['/home', '/city1']
history.push('/city2') // ['/home', '/city1', '/city2']
history.push('/city3') // ['/home', '/city1', '/city2', '/city3']
Pressing the browser back button fires a window popstate event. Pop being the keyword there. When the browser back button is pressed your history then looks like this ['/home', '/city1', '/city2'], which is why you were seeing different cities from the history.
Instead you want to use replace to achieve the desired effect
history.replace('/city1') // ['/home', '/city1']
history.replace('/city2') // ['/home', '/city2']
history.replace('/city3') // ['/home', '/city3']

Related

Refresh page before rendering component in React app

I have similar problem as in Refresh the page only once in react class component.
There are several pages in my application and I move between them using BrowserRouter and useNavigate (react-router-dom v6). One of pages has greater size div and when I go back to main page, it's(main's) css gets messed up(button position changes, some media file grows out of divs, hovers are not displayed) until I refresh page(main page). As soon as I refresh page, everything sets up well.
I used code snippet provided by #rommyarb in the link above. It works, but there is time delay (less 1sec, still visible). Which means when we navigate back(navigate(-1)), it first renders mainpage with broken css --> (0.2-0.5s) then it refreshes and css is recovered.
Time delay is not big, but still it would be unpleasant user experience. Is there any way to first refresh page (localhost/main) then render component with proper css.
Any help would be appreciated!
Code:
function App() {
return (
<Router>
<Routes>
<Route exact path='/' element={<MainPage props ={props}/>} />
<Route path='/UnderConstruction' element={<UnderConstruction/>}/>
</Routes>
</Router>
)
}
function UnderConstruction(props) {
let navigate = useNavigate();
return (
<div className='UnderConstruction' style={somestyles}>
<h2>This page is under construction</h2>
<div style={somestyles}>
<img src={under_construction.jpg'} width="100%" height="60%" />
<Button style={somestyles} onClick={() => {
navigate(-1)
}}> Go Back</Button>
</div>
</div>
);
I solved problem. The makeStyles return function(hook), when we call it within component, we can access only styles naming, which is string. So, every time we call a function, naming changes (makeStyles-element-number) due to global counter. I saved styles in state, which saved only string name. After re-rendering actual styles name was changed(makeStyles-element-number incremented) and the one I saved mismatched with actual styles. The simple solution was not storing makeStyles styles in state.
For more details read: Internal implementation of "makeStyles" in React Material-UI?

How to load a specific component when we click on a Card which takes us to an external page

I have a card item as follows : -
<CardItem
src='images/img-9.jpg'
text='Sentiment Analysis Using CNN'
label='Deep Learning'
path='/cnn-project' />
I have created a route as : -
<Route path='/cnn-project' component={() => { window.open("https://www.w3schools.com"); return null;}}/>
This is working fine .When I click on the card it takes me to the site link in new tab but the component in which I have the card changes and now just footer and the header is visible .Lets say we have card in Project component .
What I want is that after clicking the card it takes me to the site in new tab while Project component is still being displayed in my localhost 3000 ,while currently after clicking it is showing just the footer and header .
How to do that ?
Your window.open works, but simulaneously you're changing your app's path to /cnn-project, which doen't have any mapping since you return null..
Create a component you want displayed at /cnn-project route or simply go back to the previous path, like so:
const BrowserHistory = require('react-router/lib/BrowserHistory').default;
<Route path='/cnn-project' component={() => {
window.open("https://www.w3schools.com");
BrowserHistory.goBack();
return null;}}/>
edit
Just switch the Route prop from component to render and move this window.open to your new component's componentDidMount.
<Route path='/cnn-project' render={() => <MyNewComponent />} />
class MyNewComponent extends Component {
componentDidMount() {
window.open("https://www.w3schools.com");
}
...
}

Link changing URL but not the page

I am using Ant design breadcrumbs. I am trying to change the page using link and pushing the URL, I can see the URL change but the page in not changing.
I tried using Link, then creating a function for onClick but everything just change the URL.
Route:
<Route exact path="/assistant/:wId/skill/xyz/:sid" component={ xyz } />
Tried process 1:
<Breadcrumb separator=">">
<Breadcrumb.Item
onClick={this.redirectToParam2}>
{param2}
</Breadcrumb.Item>
</Breadcrumb>
redirectToParam2 = () => {
this.props.history.push(`/assistant/${wId}/skill/xyz/${sId}`);
}
Tried process 2:
<Breadcrumb separator=">">
<Breadcrumb.Item>
<Link to= {`/assistant/${wId}/skill/xyz/${sId}`}>
{param2}
</Link>
</Breadcrumb.Item>
</Breadcrumb>
Even I tried without the Breadcrumbs component but it's still not changing the page.
I want the page to change as soon as the URL changes.
Thank you in advance.
Try this,
import { Link } from "react-router-dom";
<Breadcrumb separator=">">
<Breadcrumb.Item>
<Link to= {`/assistant/${wId}/skill/xyz/${sId}`}>
{param2}
</Link>
</Breadcrumb.Item>
</Breadcrumb>
The problem you are running into, is that with changing the parameters used as props for the xyz component, the component is not replaced but gets new properties. Since nothing changes, i'm assuming you have state that gets filled either in the constructor or ComponentWillMount/ComponentDidMount.
React class components have a lifecycle function for this: componentDidUpdate.
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).
Quote from react docs, See: https://reactjs.org/docs/react-component.html#componentdidupdate
componentDidUpdate(prevProps) {
if ((this.props.params.match.sid !== prevProps.params.match.sid) ||
(this.props.params.match.wid !== prevProps.params.match.wid)) {
this.populateState(this.props.params.match); //fill your state
}
}

how to implement website navigation with reactjs

Hi I am developing a website using reactjs. Each page of the website has mainly 3 parts (1. header 2. body 3. footer) . So header and footer will be same for each page and body will keep on changing. Should I create header and footer components and then include them in each page of the website. Is this good design?
How can I highlight navigation menu option for a particular page. For example If I am on contactus page then ContactUs menu option should be highlighted. Similarly If I am one Home Page then "Home" should be highlighted.
In react apps you usually use a router library for this.
A router also takes care of the url in the address bar, so you can save and share links to sub pages in a single page application, and use the browser's back button.
The most popular router for react is called "React Router", but there are other alternatives. It's even possible to write your own router.
React-router's docs has examples of how you can implement this. For the highlighting effect, you can use the component called <NavLink />
Instead of including the header and footer in each page, you start from the outside in. You only put header and footer in once, typically in a main <App />, and then include variable page content inside <Route /> components.
yes you can create 2 components on the top level. they will be header and footer. for navigation; you can use react-router. it will be used to navigate between views. you can put the body component inside your header component your main App structure can be :-
<App>
<HeaderComp/>
<FooterComp/>
</App>
now you can set react-router to change the component being render in body place when any link in the header is clicked. you can also keep the state of currently active view and highlight its color when active.
in react-router v4 you can use switch and route to change between components
<Switch>
<Route exact path='/' component={YourComponent} />
<Route path='/secondcomponent' component={YourSecondComponent} />
<Route path='/thirdcomponent' component={YourthirdComponent} />
</Switch>
this will be your body component , other components like given above will be shown when you click on the link in the head that matches the path in Route tag.
now you header render can be like this.
render(){
return (
<div>
<TopBar/>
<BodyComp/>
<div/>
)
}
the topbar will be fixed and stay on top , the body will have all the space except the margin on top to adjust below the topbar
your topbar can be like this.
render(){
return(
<div className="topBarcontainer">
<Link to="/" >
<div className ="topBarItem">
Home
</div>
</Link>
<Link to="/secondComponent" >
<div className ="topBarItem">
secondComponent
</div>
</Link>
</div>
)
}
as for you want to highlight the current view , you can keep the state array and add give each Link the value from that array , and put onMouseDown on it , when it is clicked it will callback telling the value that is clicked and u will reset all the items background color to default , then you can set the style of that particular active item in your header to active color. you should use inline styling for that instead of className

switching between certain component on a page using nested route in react router

I am trying to create a job site. Following pages shows list of all the jobs which is shown once user hits search button from home page. So basically this is the second page.
In this page i am catching all the search parameter from url and fetching data from api and result is shown as below:
Once the user clicks individual joblist, detail page should load on the same page without changing header and fixed component with unique URL for the detail page. Expected result shown below:
My Problem:
I manage to create a nested Route, which renders detail page on the same page and also has a unique url. But it renders on top of existing job list. I mean if user clicks on joblist1, detail page renders on top of subsiquent list(above list: 2, 3, 4). But expected result is to only render detail page but not list of jobs when individual job list is clicked.
My code: I have only shown part of the code for brevity and simplicity.
1) jobs.js: Passes state data to child component to show list.
return(
<div>
<div>
fixed component
</div>
<div>
<RouteHandler />
<JobLists joblists={this.state.joblists} />
</div>
</div>
)
2) jobList.js: uses .map function to go through all data and handleclick function generate url and opens that url once user clicks individual link. Router catches nested route and loads value inside jobs.js in " ".
handleClick: function(i){
var base_path = window.location.protocol + '//' + window.location.host;
base_path += '/#/jobs-detail';
window.location= base_path;
},
render: function(){
var jobListRow = this.props.joblists.map(function(jobrowobj, i){
return(
<div key={jobrowobj.id} onClick={this.handleClick.bind(this, i)}>
<img src={jobrowobj.logo} alt="" />
<h3>{jobrowobj.title}</h3>
</div>
)
}.bind(this));
return(
<ul id="joblists">
{jobListRow}
</ul>
)
}
3) Route file:
var routes = (
<Route handler={App}>
<DefaultRoute handler={Home} />
<Route name="jobs" path="jobs" handler={Jobs}>
<Route name="jobs-detail" handler={JobDetail} />
</Route>
<NotFoundRoute handler={NotFoundPage} />
</Route>
);
I am not sure what is the best way to switch certain section (component) on a page as in my case switching between joblist component and jobdetail component. As you can see i am only able to load other component on top of existing component which is not the expected result.
Also would appreciate if any hint is given to maintain scroll position on the job list on user hitting back button.
I suggest you to upgrade your react-router to 1.0.0-rc1, and the API is more clear. Your problem is similar to the official introduction. The nested component will be passed as this.props.children, and you can insert it into the jobListRow.
About the scroll position, there's a github issue discussing how to restore it :)

Resources