skip to Main Content

I want these two left and right arrow buttons to be positioned left and right depending upon the props passed.

import styled from "styled-components";
import ArrowBackIosSharpIcon from '@mui/icons-material/ArrowBackIosSharp';
import ArrowForwardIosSharpIcon from '@mui/icons-material/ArrowForwardIosSharp';

const Container = styled.div`
  width: 100%;
  height: 100vh;
  display: flex;
  position: relative;
  overflow: hidden;
  background-color: #fff6a9;
`;

const Arrow = styled.div`
  width: 50px;
  height: 50px;
  background-color: #fff7f7;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  top: 0;
  bottom: 0;

  left: ${(props) => props.direction === "left" && "10px"};
  right: ${(props) => props.direction === "right" && "10px"};

  margin: auto;
  cursor: pointer;
  opacity: 0.5;
  z-index: 2;
`;

const Slider = () => {
    return (
        <Container>
            <Arrow>
                <ArrowBackIosSharpIcon direction="left" />
            </Arrow>
            <Arrow>
                <ArrowForwardIosSharpIcon direction="right" />
            </Arrow>
        </Container>
    );
}

export default Slider;

I am passing left and right as props to styled components but this is not working.

2

Answers


  1. Provide props to the Arrow component not the left arrow and right arrow.

            <Arrow direction="left">
                <ArrowBackIosSharpIcon  />
            </Arrow>
            <Arrow direction="right">
                <ArrowForwardIosSharpIcon  />
            </Arrow>
    
    Login or Signup to reply.
  2. Since you are checking the props on the ‘Arrow’ component, you will need to pass the props to it and not the ‘ArrowBackIosSharpIcon’ component. Like this:

    <Arrow direction="left">
        <ArrowBackIosSharpIcon />
    </Arrow>
    <Arrow direction="right">
        <ArrowForwardIosSharpIcon />
    </Arrow>
    

    Additionally, you can render the style property itself conditionally by replacing:

    left: ${(props) => props.direction === "left" && "10px"};
    right: ${(props) => props.direction === "right" && "10px"};
    

    with this:

    ${(props) => props.direction === "left" && "left: 10px"};
    ${(props) => props.direction === "right" && "right: 10px"};
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search