To achieve the desired behavior where dragging a multi-column WorkoutBlock results in multiple columns being displayed in the Graph, you'll need to make several modifications to your existing components. Here's a step-by-step guide along with the updated code to implement this functionality:
-
Update the WorkoutBlock Component:
- Objective: Modify the
WorkoutBlock to handle both single and multi-column blocks by passing an array of column heights.
-
Modify the WorkoutBlocks Component:
- Objective: Pass the appropriate
columns prop to each WorkoutBlock. For multi-column blocks, provide an array of heights.
-
Enhance the Graph Component:
- Objective: Adjust the
Graph to handle multiple columns from a single dropped block. This involves updating the blocks state to accommodate sub-columns and rendering them correctly.
Let's go through each step in detail.
1. Update the WorkoutBlock Component
Current Implementation:
const WorkoutBlock = ({ children, type, height }) => {
// ...
item: { type, height },
// ...
};
Updated Implementation:
import React from 'react';
import { useDrag } from 'react-dnd';
import { FiInfo } from 'react-icons/fi';
const WorkoutBlock = ({ children, type, columns = [50] }) => { // Default to single column
const [{ isDragging }, drag] = useDrag(() => ({
type: 'WORKOUT_BLOCK',
item: { type, columns }, // Pass columns array
collect: (monitor) => ({
isDragging: !!monitor.isDragging(),
}),
}));
return (
<div
ref={drag}
className={`relative bg-gray-200 rounded-lg overflow-hidden h-20 cursor-pointer ${
isDragging ? 'opacity-50' : 'opacity-100'
}`}
>
{children}
</div>
);
};
export default WorkoutBlock;
Explanation:
- Columns Prop: Introduced a
columns prop, which is an array representing the heights of each sub-column. For single-column blocks, it defaults to [50].
- Drag Item: Updated the
item to include the columns array instead of a single height.
2. Modify the WorkoutBlocks Component
Current Implementation:
<WorkoutBlock type="block50" height={50}>
<div className="absolute bottom-0 w-full h-1/2" style={{ background: '#4339F280' }}></div>
</WorkoutBlock>
// Similarly for other blocks...
Updated Implementation:
import React from 'react';
import { useDrag } from 'react-dnd';
import { FiInfo } from 'react-icons/fi';
import WorkoutBlock from './WorkoutBlock'; // Ensure correct import
const WorkoutBlocks = () => {
return (
<div className="bg-white p-6 rounded-lg shadow-md max-w-sm mx-auto">
<div className="flex justify-between items-center mb-3">
<h2 className="text-lg font-semibold">Click or drag the blocks to build workout</h2>
<FiInfo className="text-gray-400 text-2xl" />
</div>
<hr className="border-gray-300 mb-4" />
<div className="grid grid-cols-3 gap-3">
{/* Single-column blocks */}
<WorkoutBlock type="block50" columns={[50]}>
<div className="absolute bottom-0 w-full h-1/2" style={{ background: '#4339F280' }}></div>
</WorkoutBlock>
<WorkoutBlock type="block75" columns={[75]}>
<div className="absolute bottom-0 w-full h-3/4" style={{ background: '#4339F280' }}></div>
</WorkoutBlock>
<WorkoutBlock type="block30" columns={[30]}>
<div className="absolute bottom-0 w-full h-1/3" style={{ background: '#4339F280' }}></div>
</WorkoutBlock>
{/* Multi-column blocks */}
<WorkoutBlock type="block60_40" columns={[60, 40]}>
<div className="flex h-full gap-1">
<div className="w-1/2 h-3/5" style={{ background: '#4339F280' }}></div>
<div className="w-1/2 h-2/5" style={{ background: '#4339F280' }}></div>
</div>
</WorkoutBlock>
<WorkoutBlock type="block80_60_40_20" columns={[80, 60, 40, 20]}>
<div className="flex h-full gap-1">
<div className="w-1/4 h-1/5" style={{ background: '#4339F280' }}></div>
<div className="w-1/4 h-2/5" style={{ background: '#4339F280' }}></div>
<div className="w-1/4 h-3/5" style={{ background: '#4339F280' }}></div>
<div className="w-1/4 h-4/5" style={{ background: '#4339F280' }}></div>
</div>
</WorkoutBlock>
<WorkoutBlock type="block20_40_60_80" columns={[20, 40, 60, 80]}>
<div className="flex h-full gap-1">
<div className="w-1/4 h-4/5" style={{ background: '#4339F280' }}></div>
<div className="w-1/4 h-3/5" style={{ background: '#4339F280' }}></div>
<div className="w-1/4 h-2/5" style={{ background: '#4339F280' }}></div>
<div className="w-1/4 h-1/5" style={{ background: '#4339F280' }}></div>
</div>
</WorkoutBlock>
</div>
</div>
);
};
export default WorkoutBlocks;
Explanation:
- Columns Prop: For each
WorkoutBlock, explicitly pass the columns array. For instance, block60_40 has [60, 40], indicating two sub-columns with heights 60% and 40%.
3. Enhance the Graph Component
Current Implementation:
const [blocks, setBlocks] = useState([]);
// handleDrop adds single block
const handleDrop = (item) => {
if (blocks.some(block => block.type === item.type)) {
return; // Prevent duplicates
}
setBlocks((prevBlocks) => [
...prevBlocks,
{ type: item.type, height: item.height },
]);
};
Issues:
- Single Entry: Currently, each dropped block is added as a single entry, regardless of whether it's a multi-column block.
- Uniqueness Check: Prevents adding multiple same-type blocks, which might interfere with multi-column additions.
Updated Implementation:
import React, { useState } from 'react';
import { useDrop } from 'react-dnd';
const Graph = () => {
const [blocks, setBlocks] = useState([]);
const [{ isOver }, drop] = useDrop(() => ({
accept: 'WORKOUT_BLOCK',
drop: (item, monitor) => {
const offset = monitor.getClientOffset();
if (offset) {
handleDrop(item);
}
},
collect: (monitor) => ({
isOver: !!monitor.isOver(),
}),
}));
const handleDrop = (item) => {
const newColumns = item.columns.map((height, index) => ({
id: `${item.type}-${Date.now()}-${index}`, // Unique ID
type: item.type,
height,
}));
setBlocks((prevBlocks) => [...prevBlocks, ...newColumns]);
};
return (
<div
ref={drop}
className="graph-container relative w-full h-[300px] bg-[#EAEAEA] rounded-lg shadow-md p-4"
>
<div className="absolute inset-0 flex items-end space-x-2 px-2">
{blocks.map((block) => (
<div
key={block.id}
className="bg-[#4339F280] rounded"
style={{
width: `calc(${80 / blocks.length}% - 4px)`,
height: `${block.height}%`,
marginRight: '4px',
}}
/>
))}
</div>
<div className="absolute bottom-0 w-full flex justify-between text-xs mt-1">
{blocks.map((_, index) => (
<span key={index}>{index + 1} km</span>
))}
</div>
<div className="absolute left-0 top-0 h-full flex flex-col justify-between text-xs mr-1">
<span>100%</span>
<span>75%</span>
<span>50%</span>
<span>25%</span>
<span>0%</span>
</div>
</div>
);
};
export default Graph;
Explanation:
-
Removing Uniqueness Constraint:
- Removed the check that prevents adding blocks with the same
type. This is essential to allow multiple instances of the same block, especially for multi-column blocks.
-
Handling Multiple Columns:
handleDrop Function: When a block is dropped, iterate over its columns array and create a separate entry for each sub-column. Each sub-column is assigned a unique id to ensure React can efficiently render them.
- Unique IDs: Used a combination of
item.type, current timestamp (Date.now()), and the column index to generate a unique id for each sub-column.
-
Rendering Blocks:
blocks.map: Iterate over all individual columns in the blocks state and render each as a separate div with the appropriate height.
- Width Calculation: Adjusted the width calculation to evenly distribute the columns based on the total number of blocks.
-
Optional Enhancements:
- Visual Feedback: You can add visual feedback (like highlighting the drop area when a block is being dragged) by utilizing the
isOver state.
4. Final App Component (For Reference)
Ensure that your App component remains correctly configured to include the DndProvider and renders the updated WorkoutBlocks and Graph components.
import React from 'react';
import { DndProvider } from 'react-dnd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import Header from './Header';
import WorkoutBlocks from './WorkoutBlocks';
import Graph from './Graph';
function App() {
return (
<DndProvider backend={HTML5Backend}>
<div className="justify-center h-[100vh] bg-[#F8F8F8] w-full">
<Header />
{/* Main Content */}
<div className="flex justify-between mx-6 my-3 items-start">
{/* Blocks Card */}
<WorkoutBlocks />
{/* Graph Area */}
<div className="w-full ml-6">
<Graph />
</div>
</div>
</div>
</DndProvider>
);
}
export default App;
5. Summary of Changes
-
WorkoutBlock Component:
- Accepts a
columns prop (array) instead of a single height.
- Passes the
columns array in the drag item.
-
WorkoutBlocks Component:
- Defines
columns for each WorkoutBlock, using arrays for multi-column blocks.
-
Graph Component:
- Removes uniqueness constraints to allow multiple blocks of the same type.
- Handles multiple columns by adding each sub-column as a separate entry in the
blocks state.
- Uses unique IDs for each sub-column to ensure proper rendering.
6. Additional Recommendations
By following the above modifications, your application should now handle dragging multi-column WorkoutBlocks seamlessly, displaying them as separate columns within the Graph. This approach ensures scalability and maintains the integrity of both single and multi-column blocks.