I have an outer div with...
- Width
- Number of slots the outer div represents
The intent is to add a child div, but position the child div based on the start and end slot in the parent div.
To achieve this behavior, I am calculating the width per slot and the width of child div, plus the margin left of child div.
import React from 'react';
let parentDivStyle = {
border: '1px solid black',
height: '50px',
align: 'center',
display: 'inline-block'
}
let childDivStyle = {
backgroundColor: 'darkseagreen',
marginTop: '5px',
height: '40px',
}
const DivColoring = (props) => {
let parentDivWith = props.parentDivWidth;
let totalSlots = props.totalSlots;
let startSlot = props.startSlot;
let endSlot = props.endSlot;
let widthPerSlot = Math.round(parentDivWith / totalSlots);
console.log('widthPerSlot= ', widthPerSlot);
let childWidth = parentDivWith;
let marginLeft = 0;
//if startSlot is greater than 1, calculate the Left Margin and Width.
if (startSlot > 1) {
marginLeft = (startSlot - 1) * widthPerSlot;
}
//if end is present and is less than totalSlots update childWidth
if (endSlot && endSlot <= totalSlots) {
childWidth = widthPerSlot * (endSlot - startSlot + 1);
}
//add 1 px to marginLeft of child div
marginLeft = marginLeft + 1;
//remove 2 px from childWidth to add a padding of 1px at end
childWidth = childWidth - 2;
return (<div style={{ ...parentDivStyle, width: parentDivWith + 'px', }}>
<div style={{
...childDivStyle, marginLeft: marginLeft
, width: childWidth + 'px'
}}></div>
</div>);
}
export default DivColoring;
Please see the working example here https://stackblitz.com/edit/react-be8wxg
Is there any better of achieving this behavior. Thanks.