In the early stages of creating a slider where cards (divs) can be moved left and right with a click, I encountered an issue. The onClick handler is functioning properly. However, upon running the project, I noticed that the cards start 230px away from the left arrow. My goal is to have them positioned right next to the left arrow initially, with the 230px space being created (using transform: translateX
) only when the left arrow is clicked.
Project available at https://codesandbox.io/s/jolly-cache-pk4j8
Parent Component (containers/card.js)
import React,{useRef,useState} from 'react';
import { Card } from '../components';
import { CardItemContainer } from './card-item';
export function CardContainer()
{
const [scroll,setScroll]=useState('left')
return(
<Card>
<Card.ArrowSliderLeft setScroll={setScroll} />
<Card.List scroll={scroll}>
<CardItemContainer/>
<CardItemContainer/>
</Card.List>
<Card.ArrowSliderRight setScroll={setScroll} />
</Card>
)}
Child Components(componets/card/index.js)
import {ArrowBackIosOutlined,ArrowForwardIosOutlined} from "@material-ui/icons";
import React from 'react';
import {Container,Wrapper,List,ArrowSliderLeft} from './styles/card';
export default function Card({ children, ...restProps }) {
return <Container {...restProps}>{children}</Container>
}
Card.List=function CardList({scroll,children,...restProps})
{
return <List{...restProps} active={scroll}>
{children}
</List>
}
Card.ArrowSliderLeft = function HeaderArrowBackIosOutlinedSymbol({ setScroll,...restProps })
{
const handleClick =e=>{
setScroll(e)
}
return <ArrowSliderLeft {...restProps } >
<ArrowBackIosOutlined id="sliderLeft" onClick={()=>handleClick('left')}/>
</ArrowSliderLeft>
}
Card.ArrowSliderRight = function HeaderArrowForwardIosOutlinedSymbol({setScroll,...restProps}) {
const handleClick = (e) => {
setScroll(e);
};
return (
<ArrowSliderRight {...restProps}>
<ArrowForwardIosOutlined
id="sliderRight"
onClick={() => handleClick("right")}
/>
</ArrowSliderRight>
);
};
styled components (components/card/styles/card.js)
import styled from 'styled-components';
export const Container=styled.div`
width:100%;
margin-top:10px;
`
export const List=styled.div`
margin-left:50px;
display:flex;
width:max-content;
margin-top:10px;
transform:${({ active }) => (active==='left' ? 'translateX(230px)' : 'translateX(0px)')}
`
export const ArrowSliderLeft=styled.div`
`