For example I have a book list component that I want to reuse. In the mobile is used by a route, in the desktop by another route.
The book list component has links to the book. The tricky part is that the book on desktop version has links to the desktop book page url while the mobile version has links to the mobile book page url .
Example: <BookList type="large" />
Example: <BookList type="small" />
Pros:
Cons:
getBookUrl
which is called by the book list component Example: <BookList getBookUrl={(book)=>
/small/book/${book.id} } />
Example: <BookList getBookUrl={(book)=>
/large/book/${book.id} } />
Pros:
Cons:
getBookUrl
(but this function is stored in the book list component) which is called by the book list component Example: <BookList getBookUrl={BookList.getBookUrlSmall} />
Example: <BookList getBookUrl={BookList.getBookUrlLarge} />
BookList.small = {
getBookUrl: (book)=>`/small/book/${book.id}`,
}
BookList.large = {
getBookUrl: (book)=>`/large/book/${book.id}`,
}
Example: <BookList {...BookList.small} />
Example: <BookList {...BookList.large}/>
Making components explicitly-configurable (eg "small"
& "large"
) is one step away from have a responsive component (configures itself based on screen size).
But if your tactic for dealing with mobile is (sometimes) hosting a separate mobile site, this runs against the tactic of mobile components.
Regardless,
without knowing too much about your exact situation, I'd do something like this:
// BookListResponsive.js
import isMobile from "mobile-detector-of-my-choice"
import BookList from "./BookList.js"
export default props => isMobile()
? <BookList {...props} getUrl={id => `small/${id}`} />
: <BookList {...props} getUrl={id => `large/${id}`} />
It might also be worth checking out react-routers dynamic routes
<Media query={PRETTY_SMALL}>
{screenIsSmall => screenIsSmall
// small screen has no redirect
? <Switch>
<Route exact path="/invoices/dashboard" component={Dashboard}/>
<Route path="/invoices/:id" component={Invoice}/>
</Switch>
// large screen does!
: <Switch>
<Route exact path="/invoices/dashboard" component={Dashboard}/>
<Route path="/invoices/:id" component={Invoice}/>
<Redirect from="/invoices" to="/invoices/dashboard"/>
</Switch>
}
</Media>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.