const { useState } = React;
const App = () => {
const [items, setItems] = useState([]);
const [numItems, setNumItems] = useState(0);
return (
<div className="w-full">
<div className="flex p-5 align-center w-full flex-col">
<div className="flex justify-center">
<button
className="border-red-500 border-2 m-2 p-2"
onClick={() => {
addItems("Item " (numItems 1));
setNumItems(numItems 1);
}}
>
Add Item
</button>
</div>
<div className="flex flex-nowrap justify-center align-center p-2 overflow-x-auto border-2 border-blue-700">
{items.map((item) => (
<div className="m-2 p-2 border-red-800 border-2 flex-shrink-0" key={item}>
<h1>{item}</h1>
</div>
))}
</div>
</div>
</div>
);
function addItems(item) {
setItems([...items, item]);
}
};
ReactDOM.render(<App />, document.getElementById("app"));
I am using Tailwind css with React.js
In the component above, I have a button that simply adds divs horizontally to a flexbox that automatically scrolls. The issue is, I am not able to add the divs from the center i.e if I add the justify-center or justify-content: center; in normall css, the items in the beginning get clipped off. How can I keep adding items indefinitely, without losing the items and maintaining the ability to scroll?
Codepen link : https://codepen.io/vineet192/pen/jOGZQZE
CodePudding user response:
I've changed your snippet a little bit, to make it work.
Basically the clipping was because of the overflow center.
const { useState } = React;
const App = () => {
const [items, setItems] = useState([]);
const [numItems, setNumItems] = useState(0);
return (
<div className="w-full">
<div className="flex p-5 align-center w-full flex-col">
<div className="flex justify-center">
<button
className="border-red-500 border-2 m-2 p-2"
onClick={() => {
addItems("Item " (numItems 1));
setNumItems(numItems 1);
}}
>
Add Item
</button>
</div>
<div className="flex flex-nowrap justify-center align-center p-2 overflow-x-hidden border-2 border-blue-700">
<div className='flex overflow-x-auto'>
{items.map((item) => (
<div
className="m-2 p-2 border-red-800 border-2 flex-shrink-0"
key={item}
>
<h1>{item}</h1>
</div>
))}
</div>
</div>
</div>
</div>
);
function addItems(item) {
setItems([...items, item]);
}
};
ReactDOM.render(<App />, document.getElementById("app"));