const myBoxes = [
{width: 10,color: "red"},{width: 20,color: "blue"},{width: 50,color: "yellow"},{width: 30,color: "green"},{width: 40,color: "black"}
]
const Boxes = () => {
const shiftBoxes = (e) => {
//I dont kNow how to implement this
}
return (
<div>
<button onClick={shiftBoxes}>Click Me to Shift Boxes to the left by one Box</button>
<div className="Box-wrapper">
{myBoxes.map((Box) => (
<span style={{
backgroundColor: Box.color,width:`${Box.width}px`
}}> </span>
))}
</div>
</div>
);
};
ReactDOM.render(
<Boxes/>,document.body)
button {
margin: 10px 0px;}
.Box-wrapper {
border: 2px solid black;
width: 100%;
height: 60px;
display: flex;
align-content: center;
justify-content: space-between;
}
span {
padding: 20px;
margin: 10px;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Use React State to accomplish this by either transforming this component to class based component or use Hooks useState().
Using changeCSS as variable,initialise the state and set it to default as false.
shiftBoxes(){
this.setState({changeCSS: true});
}
return (
<div>
<button onClick={shiftBoxes()}>Click Me to Shift Boxes to the left by one Box</button>
<div className="box-wrapper">
{myBoxes.map((box) => (
<span style={this.changeCSS(box)}> </span>
))}
</div>
</div>
);
changeCSS(box:any){
if(this.state.changeCSS){
backgroundColor: box.color,width:`${box.width}px`
margin-left:-10%;
} else {
backgroundColor: box.color,width:`${box.width}px`enter code here`
}