I have this React Material-UI component implemented in 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>
How I can generate several Grid item from a array and add a horizontal scroll bar to list them if the list is too big?
You can use the map method to render a component for each element of your array. As for the horizontal scrolling, there are several ways to do this, but one way I've found that works well is to place the items in a flex-box container and put that container inside another container that scrolls horizontally. Also with this approach you'll need to set width: fit-content on the row component so that it expands outside of the parent component.
Let's say your data is stored in an array called items and the component for each is GridItem. Then we can do this:
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; /* for the scroll bar */
}
.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"/>