Skip to content
Advertisement

How can I render different sets of data into one React component multiple times?

I have data sets for recipes that I want to map onto cards that are on a carousel that I made.

I am trying to do this the most efficient way with least amount of code, I am already achieving it by just creating multiple sliders for each set of recipes. However I want to make it so I only need the one slider component, which already has the card component in it – in which I can then map my data into as I need. Rather than just having several of the same components where I have already mapped each dataset into previously.

Code below will show what I am trying to do.

Also here is a code sandbox if you go to the menu section and click on pasta option then the seafood button at top it will show the issue I have currently of my method of mapping is not working.

  • for reference this has been designed mobile first so UI will only look normal when in mobile dimensions.

recipeCard.js

JavaScript

menuCarousel.js

JavaScript

pastaMenuPage.js

JavaScript

and the data file incase pastaRecipes.js

JavaScript

To summarise, I am looking for a more advanced and efficient way to map data into a component so I do not need several of the same components in one file.

Advertisement

Answer

The Problem you have here is , you are telling the Slider upfront that you are going to render a certain list of items. Due to this we are repeating the Slider logic in all the places where ever we want to achieve the carousel behaviour.

But what we need is for the slider to render it contents dynamically because slider doesn’t care what it needs to render. All it needs to do is provide the carousel behaviour. This in react can be achieved using the children prop.

Create a new component for the Slider,

Solution 1

SliderContainer.js

JavaScript

Now use this component in all the places where you want to achieve the carousel behaviour.

JavaScript

Solution 2

If it is guaranteed that all the carousel items will have the below shape

JavaScript

we can further enhance the SliderContainer component to take a prop which is a list of items instead of the children prop.

JavaScript

Now with this change , we can just render the different Sliders as

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement