Last active
June 7, 2018 10:02
-
-
Save chiptus/05cd97d5d74c274c6da1cb959f485916 to your computer and use it in GitHub Desktop.
A react-router wrapper that will encapsulate the use of the router for the page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Fragment } from 'react'; | |
import { BrowserRouter, Route, Redirect } from 'react-router-dom'; | |
// this is the actual code snippet, everything afterwards is used for example | |
export function pageWrapper(Component) { | |
// can use a stateless function component, but this is easier to extend and add prop types | |
return class PageWrapper extends React.Component { | |
render() { | |
const { | |
history: { push }, | |
match: { params }, | |
} = this.props; | |
return ( | |
<Component | |
id={params.id} | |
name={params.name} | |
goToGallery={() => push('/gallery')} | |
goToImage={id => push(`/image/${id}`)} | |
goToProfile={name => push(`/profile/${name}`)} | |
/> | |
); | |
} | |
}; | |
} | |
// example of use: | |
// if we have the following components | |
const Profile = ({ name, goToGallery }) => ( | |
<div> | |
<div>Welcome {name}</div> | |
<div> | |
<button onClick={goToGallery}>Go to your gallery!</button> | |
</div> | |
</div> | |
); | |
const Image = ({ id }) => <div>Showing image {id} </div>; | |
const Gallery = ({ goToImage }) => ( | |
<div> | |
This is a gallery. Go to an{' '} | |
<button onClick={() => goToImage(1)}>image</button> | |
</div> | |
); | |
const Home = ({ goToProfile }) => ( | |
<div> | |
Welcome. Go to{' '} | |
<button onClick={() => goToProfile('Chamana')}>profile of Chamana</button> | |
</div> | |
); | |
// then our router definition can look like this: | |
const App = () => ( | |
<BrowserRouter> | |
<div> | |
<Route path="/" exact component={pageWrapper(Home)} /> | |
<Route path="/profile/:name" component={pageWrapper(Profile)} /> | |
<Route path="/gallery" component={pageWrapper(Gallery)} /> | |
<Route path="/image/:id" component={pageWrapper(Image)} /> | |
</div> | |
</BrowserRouter> | |
); | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment