N
N
nivaech2019-10-29 09:39:02
React
nivaech, 2019-10-29 09:39:02

Is there a smarter way to display content based on the route?

There is a component responsible for rendering goods in an online store. I want the component to be one, and depending on the condition, display the necessary information. In this case, the user clicked on the link of category one - the component displayed the required information, clicked on category two - it was displayed, and so on.
My solution looks something like this:

function ProductsPage({collections}) {
 return (
            <Route path="/products/type_one" render={() =>   
                <div>
                    <h1>Type One</h1>
                    <div className="products">
                    {
                        collections.category.typeOne.items.map((item) => {
                            return (
                                <ProductCard key={item.id} item={item} />
                            )
                        })
                    }
                    </div>
                </div>
            }/> 

            <Route path="/products/type_two" render={() =>   
                <div>
                    <h1>Type Two</h1>
                    <div className="products">
                    {
                        collections.category.typeTwo.items.map((item) => {
                            return (
                                <ProductCard key={item.id} item={item} />
                            )
                        })
                    }
                    </div>
                </div>
            }/> 
 )
}

I only have four subcategories so far - it looks pretty innocuous. But if there are dozens of them, then the component code will be filled with such an endless copy-paste. Is there a more elegant way to solve the problem?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Demian Smith, 2019-10-29
@nivaech

Now just (for the soul) I solve about the same problem. It all started with the fact that I did not find a satisfactory solution on the Internet for the following problems:
This is how the bike ended up https://github.com/sneas/react-nested-routes-example
The navigation hierarchy is set in a separate config . Where componentis the body of the page.
At the moment, all the components responsible for generating pages and building menus are loaded into App.js .
Generic (dynamic) page elements are placed in the Page component . Right now it only renders menus and breadcrumbs, but you can basically put anything in there.
Here is a demo: https://sneas.github.io/react-nested-routes-example/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question