Reputation: 189
In the following code I reorganize a list from bottom to top or from top to bottom.
I would rather be able to reorganize it from left to right.
Do you have any idea how to do this?
App
import React, { Component } from "react";
import FruitList from "./FruitList";
const UP = -1;
const DOWN = 1;
class App extends React.Component {
state = {
// set new state for bind key items
items: [
{ id: 1, name: "orange", bgColor: "#f9cb9c" },
{ id: 2, name: "lemon", bgColor: "#fee599" },
{ id: 3, name: "strawberry", bgColor: "#e06666" }
]
};
handleMove = (id, direction) => {
const { items } = this.state;
const position = items.findIndex(i => i.id === id);
if (position < 0) {
throw new Error("Given item not found.");
} else if (
(direction === UP && position === 0) ||
(direction === DOWN && position === items.length - 1)
) {
return; // canot move outside of array
}
const item = items[position]; // save item for later
const newItems = items.filter(i => i.id !== id); // remove item from array
newItems.splice(position + direction, 0, item);
this.setState({ items: newItems });
};
render() {
return <FruitList fruitList={this.state.items} onMove={this.handleMove} />;
}
}
export default App;
My components
import React, { Component } from "react";
const UP = -1;
const DOWN = 1;
class FruitList extends React.Component {
render() {
const { fruitList, onMove } = this.props;
return (
<div>
{fruitList.map(item => (
<div key={item.id} style={{ backgroundColor: item.bgColor }}>
<div className="fruitsId">{item.id}</div>
<div className="fruitsName">{item.name}</div>
<div className="fruitsArrows">
<a onClick={() => onMove(item.id, UP)}>▲</a>
<a onClick={() => onMove(item.id, DOWN)}>▼</a>
</div>
</div>
))}
</div>
);
}
}
export default FruitList;
Upvotes: 1
Views: 1408
Reputation: 17858
You can do this using css flexbox.
I applied { display: "flex" }
to the root div in FruitList. (The direction is default row).
FruitList.js
class FruitList extends React.Component {
render() {
const { fruitList, onMove } = this.props;
return (
<div style={{ display: "flex" }}>
{fruitList.map(item => (
<div
key={item.id}
style={{
backgroundColor: item.bgColor,
display: "flex",
}}
>
<div className="fruitsArrows">
<a onClick={() => onMove(item.id, LEFT)}>←</a>
</div>
<div className="fruitsId">{item.id}</div>
<div className="fruitsName">{item.name}</div>
<div className="fruitsArrows">
<a onClick={() => onMove(item.id, RIGHT)}>→</a>
</div>
</div>
))}
</div>
);
}
}
Upvotes: 1