I am using library called react-beautiful-dnd for draggable lists. The use case of my application is there will be a nested list which should be draggable and the items inside its corresponding list should also be draggable. The items from List1 should not be dragged to List2. For this I am trying to create draggable vertical list which is not working. The items are not draggable at all. I have created a sandbox of this either.
here it is
https://codesandbox.io/s/vqzx332zj7
The source code is
import DraggableSubItems from "./DraggableSubItems";
const reorder = (list, startIndex, endIndex) => {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
const items = [
{
id: 1,
name: "Top Level",
path: "top-level",
children: [
{
id: 1,
name: "dropbox",
path: "dropbox"
},
{
id: 2,
name: "asana",
path: "asana"
}
]
},
{
id: 2,
name: "Frontend Library",
path: "frontend-library",
children: [
{
id: 1,
name: "reactjs",
path: "reactjs"
},
{
id: 2,
name: "vuejs",
path: "vuejs"
}
]
}
];
const grid = 8;
const getListStyle = () => ({
padding: grid,
display: "flex",
flexDirection: "column"
});
class DraggableItems extends React.Component {
constructor(props) {
super(props);
this.state = {
items
};
}
onDragEnd = result => {
console.log("drag", result);
// dropped outside the list
if (!result.destination) {
return null;
}
if (result.destination.index === result.source.index) {
return;
}
const items = reorder(
this.state.items,
result.source.index,
result.destination.index
);
console.log("items", items);
this.setState({
items
});
};
render() {
return (
<DragDropContext onDragEnd={this.onDragEnd}>
<Droppable droppableId="droppable">
{(provided, snapshot) => {
console.log("provided", provided, snapshot);
return (
<div
ref={provided.innerRef}
style={getListStyle(snapshot.isDraggingOver)}
>
{this.state.items.map(item => (
<Draggable
key={item.id}
draggableId={item.id}
index={item.id}
>
{(draggableProvided, draggableSnapshot) => {
console.log(
"provided inside Draggable",
draggableProvided,
draggableSnapshot
);
return (
<React.Fragment>
<div
ref={draggableProvided.innerRef}
{...draggableProvided.draggableProps}
style={getListStyle(
draggableSnapshot.isDragging,
draggableProvided.draggableProps.style
)}
{...draggableProvided.dragHandleProps}
>
<h3>{item.name}</h3>
<DraggableSubItems
subitems={item.children ? item.children : []}
type={item.id}
/>
</div>
{draggableProvided.placeholder}
</React.Fragment>
);
}}
</Draggable>
))}
</div>
);
}}
</Droppable>
</DragDropContext>
);
}
}
export default DraggableItems;
Related
What I want is an example about how to make the drag and drop of my Table that works properly, but I cannot figure out how to make it works in (functional components)
My code :
function Preview() {
const { name } = useParams();
const [fieldsOfForm, setFieldsOfForm] = useState([]);
const [selectedForm, setSelectedForm] = useState([]);
const columns = [
{
title: 'Posição',
dataIndex: 'pos',
width: 30,
className: 'drag-visible',
render: () =>
<MenuOutlined style={{ cursor: 'grab', color: '#999' }}/>
},
{
title: "Form Name",
dataIndex: "field",
key: "field",
render: (text) => <a>{text}</a>,
},
{
title: "Tipo",
dataIndex: "fieldtype",
key: "fieldtype",
},
];
useEffect(() => {
let mounted = true;
let loadingStates = loading;
if (mounted) {
setFieldsOfForm(location.state);
loadingStates.allFields = false;
setLoading(false);
}
return () => (mounted = false);
}, [selectedForm]);
return (
//Some jsx....
<Row gutter={1}>
<Col span={1}></Col>
<Table dataSource={fieldsOfForm}
columns= {columns}/>
</Row>
// More jsx...
);
}
export default Preview;
Everything that I found on internet about this drag and drop from the lib of antd is in class component , but I wanted to make it works in my functional one.
Example that I found :
multi row drag-able table (antd)
I want some example in function component if someone has tried it already and could help me ?
Here's a functional working example:
import React from "react";
import "antd/dist/antd.css";
import { Table } from "antd";
import {
sortableContainer,
sortableElement,
sortableHandle
} from "react-sortable-hoc";
import { MenuOutlined } from "#ant-design/icons";
const data = [
{
key: "1",
name: "John Brown",
age: 32,
address: "New York No. 1 Lake Park",
index: 0
},
{
key: "2",
name: "Jim Green",
age: 42,
address: "London No. 1 Lake Park",
index: 1
},
{
key: "3",
name: "Joe Black",
age: 32,
address: "Sidney No. 1 Lake Park",
index: 2
},
{
key: "4",
name: "4",
age: 32,
address: "New York No. 1 Lake Park",
index: 3
},
{
key: "5",
name: "5",
age: 42,
address: "London No. 1 Lake Park",
index: 4
},
{
key: "6",
name: "6",
age: 32,
address: "Sidney No. 1 Lake Park",
index: 5
}
];
const DragHandle = sortableHandle(({ active }) => (
<MenuOutlined style={{ cursor: "grab", color: active ? "blue" : "#999" }} />
));
const SortableItem = sortableElement((props) => <tr {...props} />);
const SortableContainer = sortableContainer((props) => <tbody {...props} />);
function SortableTable() {
const [dataSource, setDataSource] = React.useState(data);
const [selectedItems, setSelectedItems] = React.useState([]);
const getColumns = () => {
return [
{
title: "Sort",
dataIndex: "",
width: 30,
className: "drag-visible",
render: (d, dd, i) => (
<>
<DragHandle active={selectedItems.includes(i)} />
</>
)
},
{
title: "Name",
dataIndex: "name",
className: "drag-visible"
},
{
title: "Age",
dataIndex: "age"
},
{
title: "Address",
dataIndex: "address"
}
];
};
const merge = (a, b, i = 0) => {
let aa = [...a];
return [...a.slice(0, i), ...b, ...aa.slice(i, aa.length)];
};
const onSortEnd = ({ oldIndex, newIndex }) => {
let tempDataSource = dataSource;
if (oldIndex !== newIndex) {
if (!selectedItems.length) {
let movingItem = tempDataSource[oldIndex];
tempDataSource.splice(oldIndex, 1);
tempDataSource = merge(tempDataSource, [movingItem], newIndex);
} else {
let filteredItems = [];
selectedItems.forEach((d) => {
filteredItems.push(tempDataSource[d]);
});
let newData = [];
tempDataSource.forEach((d, i) => {
if (!selectedItems.includes(i)) {
newData.push(d);
}
});
tempDataSource = [...newData];
tempDataSource = merge(tempDataSource, filteredItems, newIndex);
}
setDataSource(tempDataSource);
setSelectedItems([]);
}
};
const DraggableContainer = (props) => (
<SortableContainer
useDragHandle
disableAutoscroll
helperClass="row-dragging"
onSortEnd={onSortEnd}
{...props}
/>
);
const DraggableBodyRow = ({ className, style, ...restProps }) => {
// function findIndex base on Table rowKey props and should always be a right array index
const index = dataSource.findIndex(
(x) => x.index === restProps["data-row-key"]
);
return (
<SortableItem
index={index}
{...restProps}
selected={selectedItems.length}
onClick={(e) => {
if (e.ctrlKey || e.metaKey) {
selectedItems.includes(index)
? selectedItems.splice(selectedItems.indexOf(index), 1)
: selectedItems.push(index);
setSelectedItems(selectedItems);
} else {
setSelectedItems([]);
}
}}
/>
);
};
return (
<>
<h3>"CNTRL + Click" to select multiple items</h3>
<Table
pagination={false}
dataSource={dataSource}
columns={getColumns()}
rowKey="index"
components={{
body: {
wrapper: DraggableContainer,
row: DraggableBodyRow
}
}}
/>
{selectedItems.length ? <>{selectedItems.length} items selected </> : ""}
</>
);
}
You can play with it in Sandbox
import { useState } from "react";
function App() {
const [itemsClicked, setItemsClicked] = useState([]);
const dataList = [
{ id: 1, name: "jake" },
{ id: 12, name: "edd" },
{ id: 13, name: "john" }
];
const highlight = (data) => {
setItemsClicked((array) => {
let itemClicked = array.includes(data)
? array.filter((x, i) => x.id !== data.id)
: [...array, data]; // What I'm trying to do here is to add a new field which is 'active' >> [...array, {...data, active: true}];
return itemClicked;
});
};
return (
<div>
{dataList.map((item, i) => (
<div
style={{
borderColor: itemsClicked[i]?.active ? "1px solid green" : ""
}}
>
<button onClick={() => highlight(dataList[i])}>HIGHLIGHT</button>
</div>
))}
</div>
);
}
export default App;
What I'm trying to do here is to create a toggle which is to highlight the div.
but my problem is on the state instead of it will remove the data object, it will continue appending. how to fix it?
for example when I try to click the first data which is jake, the output should be like this in itemsClicke
[{ id: 1, name: jake, active: true }]
but when I try to click again it will just remove it from the list, but on my side, it continuing to append the data which is wrong
[{ id: 1, name: jake, active: true },{ id: 1, name: jake, active: true },{ id: 1, name: jake, active: true },{ id: 1, name: jake, active: true }]
You can simply remove the itemsClicked state and put the dataList in a state variable to have control over it:
const [dataList, setDataList] = useState([
{ id: 1, name: "jake" },
{ id: 12, name: "edd" },
{ id: 13, name: "john" }
]);
Now, you need to check an isActive property to conditionally add some styles, so you need isActive but it's not in the current dataList and you created itemsClicked to solve this issue. But there are some simpler solutions like adding a property on the fly with your dataList.
You can implement toggleHighlight function to change isActive property:
const toggleHighlight = (id) => {
setDataList((prevState) =>
prevState.map((item) =>
item.id === id ? { ...item, isActive: !item.isActive } : item
)
);
};
this toggleHandler will accept an id and take a for loop over the dataList, it finds the clicked item. if it's an active item so it changes it to false and vice versa.
let's recap and put all things together:
import { useState } from "react";
function App() {
const [dataList, setDataList] = useState([
{ id: 1, name: "jake" },
{ id: 12, name: "edd" },
{ id: 13, name: "john" }
]);
const toggleHighlight = (id) => {
setDataList((prevState) =>
prevState.map((item) =>
item.id === id ? { ...item, isActive: !item.isActive } : item
)
);
};
return (
<div>
{dataList.map((item) => (
<div
key={item.id}
style={{
display: "flex",
paddingTop: 10,
border: item.isActive ? "2px solid green" : ""
}}
>
<p style={{ padding: 5 }}>{item.name}</p>
<button onClick={() => toggleHighlight(item.id)}>HIGHLIGHT</button>
</div>
))}
</div>
);
}
export default App;
Try this on a live playground
array.includes(data)
won't return true because of this: https://stackoverflow.com/a/50371323/17357155
Just use this. It's a simple example. I used itemsClicked only for storing the ids
const highlight = (data) => {
if(itemsClicked.indexOf(data.id) == -1)
{
setItemsClicked(prevData => {
return [...prevData, data.id]
})
}
}
{
dataList.map((item, i) => (
<div
style={{
border:
itemsClicked.indexOf(item.id) > -1 ? '1px solid green' : '',
}}
>
{itemsClicked.indexOf(item.id) > -1 ? '1px solid green' : ''}
<button onClick={() => highlight(dataList[i])}>HIGHLIGHT</button>
</div>
))
}
I have many div in cascade.
and I want to apply alternated colors to my golbal div ( green, yellow for example ). But i want that colors start from the begening of the global div not from the begening of the div that contains it..
I created this using recursivity.
This is what i have ( I displayed div borders to explain the design of the page i have. )
This is what i want
React code
<div>
{
intervenants.map(i => {
return (updateListDiv(i))
})
}
</div>
const updateListDiv = (intervenant) => {
if (intervenant.children && intervenant.children.length > 0) {
return (
intervenant.children.map((int, index) => {
let n = int.name + ' ( ' + int.profile.name + ' ) '
return (<div className="a b" key={Math.random()}>
<a> {int.name} </a>
( {int.profile.name} )
{updateListDiv(int)}
</div>)
})
)
} else {
}
}
css
.a {
margin-left: 30px;
}
.b {
line-height: 24pt;
border: solid 1px black;
}
Every item needs to know the previous color. So you can store the state globally, or (probably better) pass the state to your updateListDiv function.
Here I call the state isEven:
import React from 'react';
const intervenants = [
{ name: 'a', profile: { name: 'pa' }, children: [ { name: 'a.a', profile: { name: 'pa.a' }, children: null }, { name: 'a.b', profile: { name: 'pa.b' }, children: null }, ] },
{ name: 'b', profile: { name: 'pb' }, children: [ { name: 'b.a', profile: { name: 'pb.a' }, children: null }, { name: 'b.b', profile: { name: 'pb.b' }, children: null }, ] },
{ name: 'c', profile: { name: 'pc' }, children: [ { name: 'c.a', profile: { name: 'pc.a' }, children: null }, { name: 'c.b', profile: { name: 'pc.b' }, children: null }, ] },
];
const updateListDiv = (intervenant, isEven) => {
if (!intervenant.children || intervenant.children.length < 1) {
return;
}
return (
intervenant.children.map((int, index) => {
isEven = !isEven;
return (<div
key={ index }
style={{
marginLeft: '30px',
border: 'solid 1px',
backgroundColor: isEven ? '#ff0' : '#0f0',
}}
>
{ int.name }
{ updateListDiv(int, isEven) }
</div>);
})
);
}
export const ColorTree = ()=>{
return (<div>
{ updateListDiv({ children: intervenants }, false) }
</div>);
};
Alternatively, you can pass down an overall index, and check for modulo-2.
I like this approach more, because this is more flexible (it might come in handy to have a "total" index inside the childs, and it also becomes possible to e.g. use modulo-3 or something)
const updateListDiv = (intervenant, overAllIndex) => {
// ...
return (
intervenant.children.map((int, index) => {
overAllIndex++;
return (<div
style={{
backgroundColor: (overAllIndex % 2) ? '#ff0' : '#0f0',
}}
>
{ updateListDiv(int, overAllIndex) }
</div>);
})
);
}
In the parent component manage-categories.jsx I have an array declared categoryTypes
const categoryTypes = [
{ name: "category", values: props.categories, active: true },
{ name: "type", values: props.types },
{ name: "finish", values: props.finishes },
{ name: "profile", values: props.profiles },
{ name: "thickness", values: props.thicknesses },
{ name: "ral", values: props.rals },
];
and a function selectItem that is called in the child component category-types-card.jsx
const selectItem = (item, category) => {
switch (category.name) {
case "category":
setSelectedCategoryItem(item);
break;
case "type":
setSelectedTypeItem(item);
break;
case "finish":
setSelectedFinishItem(item);
break;
case "profile":
setSelectedProfileItem(item);
break;
case "thickness":
setSelectedThicknessItem(item);
break;
case "ral":
setSelectedRalItem(item);
}
};
In the child component I need to show something for the categories that have active: true Category becomes active when it has an selectedItem.
I tried to make it active like categoryTypes[1] = { ...categoryTypes[1], active: true }; in the above switch, but in the child component the active property does not change for the certain category.
Calling the child component:
<Row className="mb-4">
{categoryTypes.map((category, index) => {
return (
<Colxx
xxs="12"
xs="6"
sm="6"
md="6"
lg="4"
xl="4"
xxl="4"
key={index}
>
<CategoryTypes
category={category}
employee={employee}
selectItem={selectItem}
selectedCategoryItem={selectedCategoryItem}
selectedTypeItem={selectedTypeItem}
selectedFinishItem={selectedFinishItem}
selectedProfileItem={selectedProfileItem}
selectedThicknessItem={selectedThicknessItem}
selectedRalItem={selectedRalItem}
/>
</Colxx>
);
})}
</Row>
How should I handle correctly this situation?
Thanks in advance!
How about passing a callback to the child component? Like so:
const ManageCategories = (props) => {
const [categoryTypes, setCategoryTypes] = useState([
{ name: "category", values: props.categories, active: true },
{ name: "type", values: props.types },
{ name: "finish", values: props.finishes },
{ name: "profile", values: props.profiles },
{ name: "thickness", values: props.thicknesses },
{ name: "ral", values: props.rals },
])
const setCategoryTypeActive = (categoryName, active) => {
setCategoryTypes((categoryTypes) =>
categoryTypes.map((categoryType) =>
categoryType.name === categoryName
? { ...categoryType, active }
: categoryType
)
)
}
return (
<Row className="mb-4">
{categoryTypes.map((category, index) => (
<Colxx xxs="12" xs="6" sm="6" md="6" lg="4" xl="4" xxl="4" key={index}>
<CategoryTypes
category={category}
employee={employee}
selectItem={selectItem}
selectedCategoryItem={selectedCategoryItem}
selectedTypeItem={selectedTypeItem}
selectedFinishItem={selectedFinishItem}
selectedProfileItem={selectedProfileItem}
selectedThicknessItem={selectedThicknessItem}
selectedRalItem={selectedRalItem}
setCategoryTypeActive={setCategoryTypeActive}
/>
</Colxx>
))}
</Row>
)
}
Then, somewhere in your child component, for example:
const CategoryTypesCard = (props) => {
props.setCategoryTypeActive("finish", true)
// ...
}
i have state hardcoded for my menu sidebar like this, how can i update value with same key from another API, all i want just update the value with same key ?
this.state = {
navList: [
{
name: 'Data Analytics',
child: []
},
{
name: 'Nelayan',
child: []
},
{
name: 'Transaksi',
child: [
{
total:0
},
{
totalDeposit:0
},
{
InputDp:0
},
{
totalCollections:0
},
{
totalProductions:0
},
{
totalShippings:0
},
{
totalShippingsDelivered:0
},
{
InputPayment:0
}
]
}
],
}
So this is my API for count all transaction each menu above
"data": {
"totalDeposit": 0,
"InputDp": 0,
"totalCollections": 1,
"totalProductions": 0,
"totalShippings": 0,
"totalShippingsDelivered": 0,
"InputPayment": 12,
"Supplier": 0,
"Buyer": 0
},
HOw can i update value with same key in react js ?
You can reach that this way:
let navList = this.state.navList;
navList.map(item => {
if (item.name === 'Nelayan') {
item.child = // the data you want in array
}
return item;
});
this.setState({ navList })
First, make a copy.
Then, you should go over each item in array and compare with the data you want to change, for example the item called 'Nelayan', and then update the content and return it to the array.
And last set the new state with the new array.
Note: You need an unique identifier to do that and be sure you are updating just the item you wanna do it for.
class App extends Component {
constructor(props) {
super(props);
this.state = {
personas: [
{ id: 1, nombre: "Adolfo" },
{ id: 2, nombre: "Juan" }
]
}
}
componentDidMount() {
console.log("componentDidMount")
let personas = this.state.personas
personas.forEach(item => {
if (item.id === 2) item.nombre = "Jose"
return item
})
this.setState({ personas })
}
render() {
console.log(this.state.personas)
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<div className="App-intro">
{
this.state.personas
? this.state.personas.map((item, index) => {
return <p key={index}>
{this.state.personas[index].id} - {this.state.personas[index].nombre}
</p>
})
: ''
}
</div>
{this.state.info ? this.state.info : 'No tengo info'}
</div>
);
}
}