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"/>