Last active
June 23, 2020 23:34
-
-
Save cassidoo/16a407f60cd2ff730049bc1c33589210 to your computer and use it in GitHub Desktop.
A React Router example
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
// This is the main layout of the whole website for selling some products | |
export default function PrimaryLayout() { | |
return ( | |
<> | |
<Header /> | |
<main> | |
<Switch> | |
<Route path="/" exact> | |
<Home /> | |
</Route> | |
<Route path="/products"> | |
<ProductsLayout /> | |
</Route> | |
</Switch> | |
</main> | |
<footer> | |
whatever | |
</footer> | |
</> | |
) | |
} | |
// When you go to the /products route, you have a sidebar on the page, and then you | |
// can navigate between other things in the main part | |
function ProductsLayout() { | |
return ( | |
<div className="products-layout"> | |
<aside className="sidebar"> | |
<Heading size={3}>Categories</Heading> | |
<Filter>Computers</Filter> | |
<Filter>Games</Filter> | |
<Filter>Music</Filter> | |
</aside> | |
<main> | |
<Switch> | |
<Route path="/products" exact> | |
<BrowseProducts /> | |
</Route> | |
<Route path="/products/:productId"> | |
<ProductProfile /> | |
</Route> | |
</Switch> | |
</main> | |
</div> | |
) | |
} | |
// When you nagivate to /products/:productId, you will still see the sidebar | |
// from the ProductsLayout, and you can pull in data based on the productId | |
function ProductProfile() { | |
let { productId } = useParams() | |
// Cart | |
const { addToCart, getQuantity } = useShoppingCart() | |
const quantity = getQuantity(productId) | |
// Get Product | |
const getProduct = useCallback(() => api.getProduct(productId), [productId]) | |
const [product] = usePromise(getProduct) | |
if (!product) return <div>Loading...</div> | |
// In here I just list the products, but you could make it so you could click in to related product routes, | |
// **based on the data we get from the API** | |
return ( | |
<div> | |
<ProductImage src={product.imagePath} alt={product.name} size={15} /> | |
<Heading>{product.name}</Heading> | |
<strong>{product.price}</strong> | |
<div>Category: {product.category}</div> | |
<ShoppingCartButton | |
onClick={() => addToCart(productId, product.name, product.price)} | |
quantity={quantity} | |
/> | |
</div> | |
) | |
} // the addToCart could also toggle a "cart size" thing and you could add a conditional route based on the size being > 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment