Create objects in the gallery

I recently developed a React Material-UI component using Typescript:

<Grid container direction="row" justifyContent="flex-start" alignItems="flex-start">
                <Grid item xs={5}>
                    <Box m={5} pl={10}>
                        ...... some body text..........
                    </Box>
                </Grid>
            </Grid>

Is there a way to dynamically generate multiple Grid items from an array and include a horizontal scroll bar if the list becomes too large?

Answer №1

To display a component for each item in an array, utilize the map method. For horizontal scrolling functionality, one effective approach is to nest the items in a flex-box container within another container that scrolls horizontally. It is important to set the width: fit-content property on the row component to allow it to expand beyond its parent element.

Assuming your data is stored in an array named items, and the component used for rendering each item is GridItem, you can implement the following:

function App() {
  const items = [{name: "One"}, {name: "Two"}, {name: "Three"}, {name: "Four"}, {name: "Five"}, {name: "Six"}];
  
  return (
    <div className="scroll-wrapper">
      <div className="row">
        {items.map(e => <GridItem name={e.name}/>)}
      </div>
    </div>
  )
}

function GridItem({ name }) {
  return (
    <div className="grid-item">
      {name}
    </div>
  )
}

ReactDOM.render(<App/>, document.querySelector("#root"));
.scroll-wrapper {
  overflow-x: scroll;
  padding-bottom: 1rem; /* scrollbar spacing */
}

.row {
  display: flex;
  flex-direction: row;
  width: fit-content;
}

.grid-item {
  width: 30vw;
  padding: 0.25rem 0.5rem;
  border: 1px solid black;
  margin-right: 1rem;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


<div id="root"/>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: An issue occurred with the tasks in the Gruntfile.js file

pm WARN EPACKAGEJSON <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="74041506001a1106041b0600151834445a445a44">[email protected]</a> No description npm WARN EPACKAGEJSON <a href="/cdn-cgi/l/email-protection" ...

transferring data to and from a secure website

Excuse my confusion, but I am feeling a bit overwhelmed with this situation. My coworkers and I have been working on a project where I developed a website using HTTPS, while another colleague set up a webserver. To access my website, I found that I can typ ...

Is there a way to dynamically expand and collapse all table rows, with the latest row always remaining visible, using pure JavaScript?

I have a form input field where I enter data. The entered data is then displayed in a table as a new row, with the most recent entry at the top. What I want to achieve is to show only the newest row in the table and hide all other rows. When I hover over ...

Surprising Outcomes of Negative Margin in jQuery Animation

Unique Project Summary I am currently working on a website that incorporates a sliding menu feature. I have successfully implemented this functionality, and the display remains consistent during the animation transitions for sliding the menu in and out. T ...

Effortlessly transition a div with seamless animation as it moves across the screen

I need help with an absolutely positioned div: class MyDiv extends React.Component { state = { stepCount: 0 }; componentDidMount(){ setInterval(() => { this.setState({ stepCount: this.state.stepCount + 1 }) }, 1000); } ren ...

Error message: Trying to call the prepare() function on a null variable within the CRUD system

I have implemented a CRUD system on my website. The main page (avisos.php) displays a table with all the existing records. When a user clicks on the "ADD NEW RECORD" button, the following script is triggered: $("#btn-add").click(function(){ $(".co ...

What is the best way to represent a directory structure in JSON using a C# data type?

My directory structure is as follows: v1 file1.txt file2.txt common common.txt I need to create a C# function that can traverse this directory structure and generate JSON output. The expected JSON format is like this: { "v1&qu ...

How can I apply CSS properties to a div class by targeting another child div class?

When the div class dhx_list_item dhx_list_day_events_item is present, I need to apply the following CSS: .dhx_view .day_events .dhx_scroll_cont:first-of-type:before { //some code here } Please see the attachment for reference. ...

Exploring portfinder in Javascript: A guide to its usage

As a newcomer to Javascript, I am eager to figure out how to utilize the portfinder.getPort() function within one of my functions in order to generate a random port each time. The code snippet below showcases my current implementation: var portfinder = re ...

Injecting resolve values from UI router into Angular Jasmine tests

I am facing an issue in my Angular application where UI router resolves a promise into the controller. However, when attempting to test this controller using Karma, I receive an error about an unknown provider. How can I inject a mock object into the test ...

Guide to calculating the total sum of array elements on a monthly basis using React

[ { "id": 305, "date_created": "2021-03-20T09:25:45", "sale": "3000.00", }, { "id": 306, "date_created": "2021-04-05T14:30:20", ...

C++ engine for embedding HTML, CSS, and scripts

I am working on a C++ Windows native application and I'm looking for an HTML engine to help with displaying data in the GUI. After some searching, I came across Sciter, which seems like a good fit. However, I've noticed that it lacks complete CS ...

Why isn't the length of the Array changing when using React's useState hook

I am facing a challenge trying to understand why the value of inputElementArray.length consistently remains 0 when accessed within the useEffect method. function view() { const [inputElementArray, setInputElementArray] = useState<HTMLInputElement[]& ...

What is the process for rendering a React class component using React HashRouter and Apollo client?

I've run into an issue with my project that involves using only React class components and fetching data from an Apollo server. The problem I'm facing is that, in Chrome, only the Navbar.jsx component is rendering. Even when I navigate to one o ...

The Kendo Grid is not displaying any data when trying to bind the data source using an ajax callback to the controller

My query is quite similar in nature to this: Binding Kendo Data Source with Async $.ajax calling from C# MVC Controller Action Below is the javascript code used for generating the Kendo grid: $(document).ready(function () { $("#grid").kendo ...

"Executing the command 'npm run dev' is successful, however, the command 'next dev' does not yield the expected result

Trying out Next for the first time using npx create-next-app, but running into issues with the scripts. While npm run dev works without any problems, executing next dev gives me an error saying zsh: command not found: next. Any idea why this is happening? ...

Injecting arbitrary text following ?= in a web URL

Consider the following code snippet for a page named MyWebsite.com/page.php <?php $username = "SuperUsername"; $password = "SuperPassword"; if (isset($_GET['p']) && $_GET['p'] == "login") { if ($_POST['user&ap ...

Mastering the art of creating an authentic carbon fiber CSS background

Authentic carbon fiber consists of a series of interconnected grey fibers that resemble woven sheets in grey color. Does anyone have knowledge on how to replicate this pattern using CSS? The examples created by Lea Verou do not accurately depict true carb ...

When the ajax response comes in, my javascript code seems to suddenly stop

After sending a POST request, my JavaScript suddenly stops working for some unknown reason. Here's the situation: I visit my webpage, fill out the form, and then click 'Click me' : Upon clicking OK in the alert popup, I see the expected ou ...

The instance does not have a definition for the property or method "foo" that was referenced during rendering

[Vue warn]: Property or method "modelInfo" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. Whenever I ...