Reputation: 58
import React, { Component } from 'react'
import Head from './Head'
import Popular from './Popular'
import Movie from './Movie'
import Search from './Search'
class Flix extends Component {
constructor() {
super()
this.state = {
id : 0,
}
}
fetchDetails = (id) => {
this.setState({id : id})
}
render() {
var dialogue //this is an array which I pass to Head
if (this.state.id === 0) {
return (
<div>
<Head subHeading={dialogue} />
<Search />
<Popular fetchDetails={this.fetchDetails}/>
</div>
);
} else {
return (
<div>
<Head subHeading={dialogue} />
<Search/>
<Movie id={this.state.id} />
</div>
);
}
}
}
export default Flix;
So, what is happening is, Popular displays a list of popular movies and when user clicks on a movie it reutns the 'id' of that movie and that is passed to Movies to display more information about the clicked movie.
This whole system works and onclick I get more details about that movie but the way I have implemented this is that at start id=0 so, display popular movies and onclick id changes to some number than according to that display Movie details.
I used simple if statement for this.
My problem is as there is no back button how can implement a way such that after user gets the details he wants to come back to popular movies to the point where he scrolled down the list of popular movies. Basically like a back button.
At this point back button on browser doesn't work.
Upvotes: 2
Views: 69
Reputation: 509
If you want to be able to use the back button, you may be best served by implementing the react router (specifically react-router-dom if this is web-based). Here is a good tutorial for the current version: https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf. Then you could set your state based on the browser path.
Filling out actual changes to your URL might be more ambitious than you were wanting right off hand, but it does open other possibilities such as permalinking individual results while still keeping your app as a single-page app.
Upvotes: 2
Reputation: 2263
Get the offset of the window when showing the details and save it to the tate with something like:
this.setState ({
scrollOffset: window.scrollTop
})
Then a button (or a Link or whatever component you want) and onClick bind a simple function that does this:
handleButton = () => {
this.setState({
id: 0
});
window.scrollTo(0, this.state.scrollOffset);
}
Upvotes: 4